0% found this document useful (0 votes)
2 views

javaFX

Chapter 15 focuses on event-driven programming and animations in Java, emphasizing the creation of GUI applications that respond to user actions like button clicks. It covers the concepts of events, event sources, handler classes, and the use of inner and anonymous inner classes for event handling, as well as simplifying event handling with lambda expressions. Additionally, the chapter introduces animation classes in JavaFX, demonstrating how to implement various animations and handle user interactions through mouse and keyboard events.

Uploaded by

jrnckyt4dr
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

javaFX

Chapter 15 focuses on event-driven programming and animations in Java, emphasizing the creation of GUI applications that respond to user actions like button clicks. It covers the concepts of events, event sources, handler classes, and the use of inner and anonymous inner classes for event handling, as well as simplifying event handling with lambda expressions. Additionally, the chapter introduces animation classes in JavaFX, demonstrating how to implement various animations and handle user interactions through mouse and keyboard events.

Uploaded by

jrnckyt4dr
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 75

Chapter 15 Event-Driven

Programming and Animations

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
1
Motivations
Suppose you want to write a GUI
program that lets the user enter a
loan amount, annual interest rate,
and number of years and click the
Compute Payment button to obtain
the monthly payment and total
payment. How do you accomplish
the task? You have to use event-
driven programming to write the Loan Calculator
code to respond to the button-
clicking event.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
2
Objectives
▪ To get a taste of event-driven programming (§15.1).
▪ To describe events, event sources, and event classes (§15.2).
▪ To define handler classes, register handler objects with the source object, and write
the code to handle events (§15.3).
▪ To define handler classes using inner classes (§15.4).
▪ To define handler classes using anonymous inner classes (§15.5).
▪ To simplify event handling using lambda expressions (§15.6).
▪ To develop a GUI application for a loan calculator (§15.7).
▪ To write programs to deal with MouseEvents (§15.8).
▪ To write programs to deal with KeyEvents (§15.9).
▪ To create listeners for processing a value change in an observable object (§15.10).
▪ To use the Animation, PathTransition, FadeTransition, and Timeline classes to
develop animations (§15.11).
▪ To develop an animation for simulating a bouncing ball (§15.12).

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
3
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, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
4
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

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
5
Handling GUI Events

Source object (e.g., button)


Listener object contains a method for
processing the event.

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
6
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<ActionEvent> {


@Override
public void handle(ActionEvent e) {
System.out.println("OK button clicked");
}
}
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
7
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<ActionEvent> {


@Override
public void handle(ActionEvent e) {
System.out.println("OK button clicked");
}
}
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
8
animation
Trace Execution
public class HandleEvent extends Application {
public void start(Stage primaryStage) { 3. Click OK. The
… JVM invokes the
OKHandlerClass handler1 = new OKHandlerClass(); listener’s handle
btOK.setOnAction(handler1); method
CancelHandlerClass handler2 = new CancelHandlerClass();
btCancel.setOnAction(handler2);

primaryStage.show(); // Display the stage
}
}

class OKHandlerClass implements EventHandler<ActionEvent> {


@Override
public void handle(ActionEvent e) {
System.out.println("OK button clicked");
}
}
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
9
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, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
10
Event Classes

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
11
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, component
events, mouse movements, and keystrokes. Table
16.1 lists external user actions, source objects, and
event types generated.

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
12
Selected User Actions and Handlers

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
13
The Delegation Model

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
14
The Delegation Model: Example

Button btOK = new Button("OK");


OKHandlerClass handler = new OKHandlerClass();
btOK.setOnAction(handler);

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
15
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

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
16
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

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
17
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, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
18
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, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
19
Inner Classes, cont.

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
20
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, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
21
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. A
static inner class can be accessed using
the outer class name. A static inner class
cannot access nonstatic members of the
outer class
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
22
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, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
23
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, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
24
Anonymous Inner Classes (cont.)

AnonymousHandlerDemo
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
25
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<ActionEvent>() { // 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, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
26
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, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
27
Single Abstract Method Interface (SAM)
The statements in the lambda expression is all for
that method. If it contains multiple methods, the
compiler will not be able to compile the lambda
expression. So, for the compiler to understand
lambda expressions, the interface must contain
exactly one abstract method. Such an interface is
known as a functional interface, or a Single Abstract
Method (SAM) interface.
AnonymousHandlerDemo
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
28
Problem: Loan Calculator

LoanCalculator

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
29
MouseEvent

MouseEventDemo
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
30
The KeyEvent Class

MouseEventDemo
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
31
The KeyCode Constants

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
32
Example: Control Circle with Mouse
and Key

ControlCircleWithMouseAndKey

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
33
Listeners for Observable Objects
You can add a listener to process a value change in an
observable object.
An instance of Observable is known as an observable object,
which contains the addListener(InvalidationListener
listener) method for adding a listener. Once the value is
changed in the property, a listener is notified. The listener class
should implement the InvalidationListener interface, which
uses the invalidated(Observable o) method to handle the
property value change. Every binding property is an instance of
Observable.
ObservablePropertyDemo

DisplayResizableClock
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
34
Animation
JavaFX provides the Animation class with the core
functionality for all animations.

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
35
PathTransition

PathTransitionDemo

FlagRisingAnimation
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
36
FadeTransition
The FadeTransition class animates the change of the
opacity in a node over a given time.

FadeTransitionDemo
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
37
Timeline
PathTransition and FadeTransition define specialized
animations. The Timeline class can be used to program any
animation using one or more KeyFrames. Each
KeyFrame is executed sequentially at a specified time
interval. Timeline inherits from Animation.

TimelineDemo

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
38
Clock Animation

ClockAnimation
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
39
Case Study: Bouncing Ball

BallPane

BounceBallControl

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
40
Chapter 14 JavaFX Basics

Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
1
Motivations
JavaFX is a new framework for developing Java
GUI programs. The JavaFX API is an excellent
example of how the object-oriented principle is
applied. This chapter serves two purposes. First, it
presents the basics of JavaFX programming.
Second, it uses JavaFX to demonstrate OOP.
Specifically, this chapter introduces the framework
of JavaFX and discusses JavaFX GUI components
and their relationships.

Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
2
Objectives
❑ To distinguish between JavaFX, Swing, and AWT (§14.2).
❑ To write a simple JavaFX program and understand the relationship among stages,
scenes, and nodes (§14.3).
❑ To create user interfaces using panes, UI controls, and shapes (§14.4).
❑ To use binding properties to synchronize property values (§14.5).
❑ To use the common properties style and rotate for nodes (§14.6).
❑ To create colors using the Color class (§14.7).
❑ To create fonts using the Font class (§14.8).
❑ To create images using the Image class and to create image views using the
ImageView class (§14.9).
❑ To layout nodes using Pane, StackPane, FlowPane, GridPane, BorderPane, HBox,
and VBox (§14.10).
❑ To display text using the Text class and create shapes using Line, Circle, Rectangle,
Ellipse, Arc, Polygon, and Polyline (§14.11).
❑ To develop the reusable GUI components ClockPane for displaying an analog clock
(§14.12).

Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
3
JavaFX vs Swing and AWT
Swing and AWT are replaced by the JavaFX platform for
developing rich Internet applications.

When Java was introduced, the GUI classes were bundled in a


library known as the Abstract Windows Toolkit (AWT). AWT is
fine for developing simple graphical user interfaces, but not for
developing comprehensive GUI projects. In addition, AWT is
prone to platform-specific bugs. The AWT user-interface
components were replaced by a more robust, versatile, and
flexible library known as Swing components. Swing components
are painted directly on canvases using Java code. Swing
components depend less on the target platform and use less of the
native GUI resource. With the release of Java 8, Swing is
replaced by a completely new GUI platform known as JavaFX.

Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
4
Basic Structure of JavaFX
▪ Application
▪ Override the start(Stage) method
▪ Stage, Scene, and Nodes
Stage
Scene

Button

MyJavaFX

MultipleStageDemo

Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
5
Panes, UI Controls, and Shapes

ButtonInPane
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
6
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

Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
7
Binding Properties
JavaFX introduces a new concept called binding property
that enables a target object to be bound to a source object.
If the value in the source object changes, the target
property is also changed automatically. The target object is
simply called a binding object or a binding property.

ShowCircleCentered

Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
8
Binding Property:
getter, setter, and property getter

Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
9
Uni/Bidirectional Binding

BindingDemo

BidirectionalBindingDemo

Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
10
Common Properties and Methods
for Nodes
▪ style: set a JavaFX CSS style

▪ rotate: Rotate a node

NodeStyleRotateDemo

Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
11
The Color Class

Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
12
The Font Class

FontDemo

Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
13
The Image Class

Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
14
The ImageView Class

ShowImage

Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
15
Layout Panes
JavaFX provides many types of panes for organizing nodes
in a container.

Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
16
FlowPane

MultipleStageDemo
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
17
GridPane

ShowGridPane

Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
18
BorderPane

ShowBorderPane

Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
19
HBox

Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
20
VBox

ShowHBoxVBox

Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
21
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.
22
Text

Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
23
Text Example

ShowText

Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
24
Line

ShowLine

Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
25
Rectangle

Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
26
Rectangle Example

ShowRectangle

Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
27
Circle

Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
28
Ellipse

radiusX radiusY
(centerX, centerY)

ShowEllipse

Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
29
Arc

Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
30
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

Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
31
Polygon and Polyline

Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
32
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<Double>

ShowPolygon

Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
33
Case Study: The ClockPane Class
This case study develops a class that displays a clock on a
pane.

javafx.scene.layout.Panel The getter and setter methods for


-char token these data fields are provided in the class,
but omitted in the UML diagram for brevity.
+getToken
+setToken ClockPane
+paintComponet
+mouseClicked
-hour: int The hour in the clock.
-minute: int The minute in the clock.
-second: int The second in the clock.

+ClockPane() Constructs a default clock for the current time.


+ClockPane(hour: int, minute: int, Constructs a clock with the specified time.
second: int)
+setCurrentTime(): void Sets hour, minute, and second for current time.
+setWidth(width: double): void Sets clock pane’s width and repaint the clock,
+setHeightTime(height: double): void Sets clock pane’s height and repaint the clock,

ClockPane
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
34
Use the ClockPane Class

DisplayClock

Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
35

You might also like