SWE211 - Lect10 - JavaFX Event Driven Programming and Graphics PDF
Document Details
Uploaded by Deleted User
Tags
Summary
This document provides a lecture on JavaFX, focusing on event-driven programming concepts and graphics. It includes example code snippets showcasing the key components of event handling.
Full Transcript
Object Oriented Programming SWE211 Outlines GUI in Java Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. Procedural vs. Event-Driven...
Object Oriented Programming SWE211 Outlines GUI in Java Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. Procedural vs. Event-Driven Programming Procedural programming is executed in procedural order. In event-driven programming, code is executed upon activation of events. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 3 Taste of Event-Driven Programming The example displays a button in the frame. A message is displayed on the console when a button is clicked. HandleEvent Run Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 4 Handling GUI Events Source object (e.g., button) Listener object contains a method for processing the event. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 5 animation Trace Execution public class HandleEvent extends Application { public void start(Stage primaryStage) { 1. Start from the … main method to OKHandlerClass handler1 = new OKHandlerClass(); create a window and btOK.setOnAction(handler1); display it CancelHandlerClass handler2 = new CancelHandlerClass(); btCancel.setOnAction(handler2); … primaryStage.show(); // Display the stage } } class OKHandlerClass implements EventHandler { @Override public void handle(ActionEvent e) { System.out.println("OK button clicked"); } } Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 6 animation Trace Execution public class HandleEvent extends Application { public void start(Stage primaryStage) { 2. Click OK … OKHandlerClass handler1 = new OKHandlerClass(); btOK.setOnAction(handler1); CancelHandlerClass handler2 = new CancelHandlerClass(); btCancel.setOnAction(handler2); … primaryStage.show(); // Display the stage } } class OKHandlerClass implements EventHandler { @Override public void handle(ActionEvent e) { System.out.println("OK button clicked"); } } Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 7 animation Trace Execution public class HandleEvent extends Application { public void start(Stage primaryStage) { 3. The JVM invokes … the listener’s handle OKHandlerClass handler1 = new OKHandlerClass(); method btOK.setOnAction(handler1); CancelHandlerClass handler2 = new CancelHandlerClass(); btCancel.setOnAction(handler2); … primaryStage.show(); // Display the stage } } class OKHandlerClass implements EventHandler { @Override public void handle(ActionEvent e) { System.out.println("OK button clicked"); } } Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 8 Events An event can be defined as a type of signal to the program that something has happened. The event is generated by external user actions such as mouse movements, mouse clicks, or keystrokes. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 9 Event Classes Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 10 Event Information An event object contains whatever properties are pertinent to the event. You can identify the source object of the event using the getSource() instance method in the EventObject class. The subclasses of EventObject deal with special types of events, such as button actions, window events, mouse movements, and keystrokes. Table 15.1 lists external user actions, source objects, and event types generated. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 11 Selected User Actions and Handlers Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 12 The Delegation Model Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 13 Implementing an EventHandler The EventHandler interface is a generic interface, which means that you must specify the specific event type that the interface will implement. In this case, the class will handle ActionEvent events. interface EventHandler The EventHandler interface has one method heading that must be implemented void handle(T Event ) // part of Java; you don't write this public interface EventHandler< ActionEvent > { public void handle(ActionEvent e); } Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. The Delegation Model: Example class OKHandlerClass implements EventHandler { public void handle(ActionEvent e) { //code to handle the event; } } // EX: Prints a message when the button is clicked. class OKHandlerClass implements EventHandler { public void handle(ActionEvent e) { System.out.println("OK button clicked"); } } Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. Attaching an ActionListener Button and other graphical controls have this method: public void setOnAction(EventHandler handler) Button btOK = new Button("OK") OKHandlerClass handler1 = new OKHandlerClass(); btOK.setOnAction(handler1); now OK button will print " OK button clicked " when clicked setOnAction method exists in many JavaFX components Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. In order to set up this relationship, a GUI program must do the following things. 1. Create a GUI component on the GUI 2. Define the EventHandler class that represents the event handler. - this class should implement an appropriate listener interface 3. Create an object of event listener class, and register this object with the GUI component - setOnAction method Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. OK button clicked Cancel button clicked Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 18 Add button and label. when the button is clicked, the number is incremented. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 19 From the above code: (1) We need to import (2) The handle method has a single ActionEvent argument a, However, it is not used in this example. This argument contains subsidiary information about the event, which can be used for more complicated processing. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. Add 2 buttons and label. when the Add is clicked, the number is incremented. when the Subtract is clicked, the number is decremented. To determine the event source Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 21 Using Vbox pane, add textfield, button, and label. When the button is clicked the value entered in the textfield is read into an integer, incremented by one, and output into the label. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 22 Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 23 Example: First Version for ControlCircle (no listeners) Now let us consider to write a program that uses two buttons to control the size of a circle. ControlCircleWithoutEventHandling Run Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 24 Example: Second Version for ControlCircle (with listener for Enlarge) Now let us consider to write a program that uses two buttons to control the size of a circle. ControlCircle Run Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 25 Inner Class Listeners A listener class is designed specifically to create a listener object for a GUI component (e.g., a button). It will not be shared by other applications. So, it is appropriate to define the listener class inside the frame class as an inner class. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 26 Inner Classes Inner class: A class is a member of another class. Advantages: In some applications, you can use an inner class to make programs simple. An inner class can reference the data and methods defined in the outer class in which it nests, so you do not need to pass the reference of the outer class to the constructor of the inner class. ShowInnerClass Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 27 Inner Classes, cont. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 28 Inner Classes (cont.) Inner classes can make programs simple and concise. An inner class supports the work of its containing outer class and is compiled into a class named OuterClassName$InnerClassName.class. For example, the inner class InnerClass in OuterClass is compiled into OuterClass$InnerClass.class. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 29 Inner Classes (cont.) An inner class can be declared public, protected, or private subject to the same visibility rules applied to a member of the class. An inner class can be declared static. o A static inner class can be accessed using the outer class name. o A static inner class cannot access nonstatic members of the outer class Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 30 Anonymous Inner Classes An anonymous inner class must always extend a superclass or implement an interface, but it cannot have an explicit extends or implements clause. An anonymous inner class must implement all the abstract methods in the superclass or in the interface. An anonymous inner class always uses the no-arg constructor from its superclass to create an instance. If an anonymous inner class implements an interface, the constructor is Object(). An anonymous inner class is compiled into a class named OuterClassName$n.class. For example, if the outer class Test has two anonymous inner classes, these two classes are compiled into Test$1.class and Test$2.class. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 31 Anonymous Inner Classes (cont.) Inner class listeners can be shortened using anonymous inner classes. An anonymous inner class is an inner class without a name. It combines declaring an inner class and creating an instance of the class in one step. An anonymous inner class is declared as follows: new SuperClassName/InterfaceName() { // Implement or override methods in superclass or interface // Other methods if necessary } Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 32 Anonymous Inner Classes (cont.) AnonymousHandlerDemo Run Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 33 Simplifying Event Handing Using Lambda Expressions Lambda expression is a new feature in Java 8. Lambda expressions can be viewed as an anonymous method with a concise syntax. For example, the following code in (a) can be greatly simplified using a lambda expression in (b) in three lines. btEnlarge.setOnAction( btEnlarge.setOnAction(e -> { new EventHandler() { // Code for processing event e @Override }); public void handle(ActionEvent e) { // Code for processing event e } } }); (a) Anonymous inner class event handler (b) Lambda expression event handler Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 34 Basic Syntax for a Lambda Expression The basic syntax for a lambda expression is either (type1 param1, type2 param2,...) -> expression or (type1 param1, type2 param2,...) -> { statements; } The data type for a parameter may be explicitly declared or implicitly inferred by the compiler. The parentheses can be omitted if there is only one parameter without an explicit data type. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 35 Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 36 Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 37 The MouseEvent Class Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 38 Drag the text Sets the value of the property onMouseDragged. MouseEventDemo Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 39 The KeyEvent Class KeyEventDemo Run Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 40 Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 41 Outlines Graphics and Animation in Java Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. Display a Shape This example displays a circle in the center of the pane. x Y Axis (0, 0) X Axis y (x, y) (0, 0) X Axis Java Conventional Coordinate Coordinate System System Y Axis ShowCircle Run Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 43 Shapes JavaFX provides many shape classes for drawing texts, lines, circles, rectangles, ellipses, arcs, polygons, and polylines. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 44 Text Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 45 Text Example Text text1 = new Text(20, 20, "Programming is fun"); text1.setFont(Font.font("Courier", FontWeight.BOLD, FontPosture.ITALIC, 15)); Text text2 = new Text(60, 60, "Programming is fun\nDisplay text"); Text text3 = new Text(10, 100, "Programming is fun\ nDisplay text"); text3.setFill(Color.RED); text3.setUnderline(true); // Underline for text3 ShowText Run text3.setStrikethrough(true); // Strikethrough for text3 Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 46 Line Line line1 = new Line(10, 10, 50, 50 ShowLine Run Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 47 Rectangle Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 48 Rectangle / Arc Rectangle ShowRectangle Run Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 49 Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 50 Circle Circle circle = new Circle(100, 100, 80); Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 51 Ellipse radiusX radiusY (centerX, centerY) ShowEllipse Run Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 52 Arc Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 53 Arc Examples radiusY length startAngle 0 degree radiusX (centerX, centerY) –30° –50° –20° 20° (a) Negative starting angle –30° and (b) Negative starting angle –50° negative spanning angle –20° and positive spanning angle 20 ° ShowArc Run Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 54 Polygon and Polyline Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 55 Polygon The getter and setter methods for property values and a getter for property javafx.scene.shape.Polygon itself are provided in the class, but omitted in the UML diagram for brevity. +Polygon() Creates an empty polygon. +Polygon(double... points) Creates a polygon with the given points. +getPoints(): Returns a list of double values as x- and y-coordinates of the points. ObservableList ShowPolygon Run Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 56 The Color Class Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 57 Color Specified as predefined Color class constants: Color.CONSTANT_NAME where CONSTANT_NAME is one of: BLACK, BLUE, CYAN, DARK_GRAY, GRAY, GREEN, LIGHT_GRAY, MAGENTA, ORANGE, PINK, RED, WHITE, YELLOW Example: Color.MAGENTA Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. Making your own colors Create colors using Red-Green-Blue (RGB) values of 0-255 Color name = new Color(red, green, blue); Color name = new Color(red, green, blue, opacity); Example: Color brown = new Color(192, 128, 64 ) Color brown = new Color(192, 128, 64,.99); Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 60 The Font Class FontDemo Run Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 61 Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 62 The Image Class The Image class represents graphical images and is used for loading images from a specified URL. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 63 The ImageView Class The ImageView is a Node used for painting images loaded with Image class. ShowImage Run Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 64 Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 65 Animation JavaFX provides the Animation class with the core functionality for all animations. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 66 To apply a particular animation to a node, you have to follow the steps given below: 1. Create a require node using respective class. 2. Instantiate the respective transition (animation) class that is to be applied 3. Set the properties of the transition and 4. Finally play the transition using the play() method of the Animation class. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 67 Transitions TranslateTransition It allows to create movement animation from one point to another within a duration. Using TranslateTransition#setByX / TranslateTransition#setByY, ScaleTransitio n To animate the scale / zoom of the given object. The object can be enlarged or minimized using this animation. RotateTransition It provides animation for rotating an object. We can provide upto what angle the node should rotate by toAngle. PathTransition, FadeTransition, SequentialTransition/ParallelTransition (combine more than Liang, one transition) Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 68 Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 69 //Create new translate transition //Go back to previous position after 0.5 seconds //Move in X axis by +200 //Repeat animation twice //Duration = 0.5 //attach the node to the transition seconds Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 70 //Marks this Event as consumed. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 71 Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 72 Exercises 1. Implement the following form to enter a person details. When click save, display details. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 73 2. Implement the simple Mickey Mouse using java Graphics. 3. Write a GUI application program to interchange the face between smile and frown when click on a button as shown below. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 74 Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved.