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

15 Slide

The document discusses event-driven programming and animations in Java. It introduces event-driven programming as an alternative to procedural programming where code is executed in response to events like button clicks rather than sequential execution. It describes how events are generated by external actions and handled by registering event handler objects with event source objects. The document outlines objectives like developing a loan calculator application and creating animations. It provides examples of detecting and handling GUI events using the delegation model in Java.

Uploaded by

Mem Mem
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views

15 Slide

The document discusses event-driven programming and animations in Java. It introduces event-driven programming as an alternative to procedural programming where code is executed in response to events like button clicks rather than sequential execution. It describes how events are generated by external actions and handled by registering event handler objects with event source objects. The document outlines objectives like developing a loan calculator application and creating animations. It provides examples of detecting and handling GUI events using the delegation model in Java.

Uploaded by

Mem Mem
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 40

CS 112 Programming 2

Lecture 14
Event-Driven Programming & Animations (1)

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
Chapter 15 Event-Driven
Programming and Animations

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 2
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
code to respond to the button-
LoanCalculator Run
clicking event.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 3
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. 4
Procedural vs. Event-Driven Programming

 Procedural programming is executed in


procedural order

 In event-driven programming, code is executed


upon activation of events. We can write code to
process events such as:
– Button clicks
– Mouse movements
– Keystrokes
– Clock events
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 5
Events and Event Sources
 An event can be defined as a type of signal
to the program that something has happened

 Event are generated by external user actions


such as mouse movements, mouse clicks, or
keystrokes. Events can also be generated by
a computer’s clock

 When an event is detected at an event


source, an event object is created. This event
object is then passed on to an event handler
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
6
rights reserved.
Example: Event-Driven Program
1. Extend Application and
Displays two override start(Stage)
buttons and display 2. Create nodes
a message on the 3. Create event handlers by
console when a implementing EventHandler<>
and overriding handle()
button is clicked 4. Register event handlers with
event sources (e.g. nodes) using
event registration methods
5. Place node in a Parent
6. Place the Parent in the Scene
HandleEvent Run 7. Place the Scene on Stage
8. Show Stage
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 7
Detecting & Handling GUI Events

 A source object can detect several types of events


 Several different event handlers may be registered with
a single source object to handle different types of events
 When an event occurs, an event object with info on the
source object and the specifics of the event is created
 This event object is then handled by the appropriate
event handler registered with the source object
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) { 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. 9
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. 10
animation
Trace Execution
public class HandleEvent extends Application {
public void start(Stage primaryStage) { 3. The JVM invokes
… the handler’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<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. 11
Event Classes

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 12
Contents of the Event Object
 An event object contains whatever
properties are pertinent to the event
– For example, we can identify the source object
of the event using getSource() in the
EventObject class

 Subclasses of EventObject deal with


special types of events, such as button
actions, window events, mouse
movements, and keystrokes
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 13
Selected User Actions & Handlers

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 14
The Delegation Model
Java uses a delegation-based model for event handling: a source object fires
an event, and a handler (or listener) object interested in the event handles it,
i.e. the source object delegates the handling of the event to the handler object

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

Button btOK = new Button("OK");


OKHandlerClass handler = new OKHandlerClass();
btOK.setOnAction(handler); //register listener

Source Listener

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 16
Example: Event Handling
We would like to use buttons to control the size of a circle

ControlCircleWithoutEventHandling Run

ControlCircle Run

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 17
Inner Class Listeners
 A listener (or handler) class is designed
specifically to create a listener object for a
GUI component (e.g., a button)
 As it will not be shared by other
applications, it is appropriate to define the
listener class inside the main class as an
inner class

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 18
Inner Classes
 An inner class, or nested class, is a class
defined within the scope of another class. In
some applications, inner classes make the
program easier to understand
 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
ShowInnerClass
of the inner class
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 19
Example: Inner Classes

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 20
Inner Classes (cont.)
 An inner class supports the work of its outer class and is
compiled into a class named
OuterClassName$InnerClassName.class
– Example: inner class B in outer class A is compiles to A$B.class

 An inner class can be declared subject to the same visibility


rules applied to any other member of a class

 An inner class can be declared static, but it cannot access


non-static members of the outer class. A static inner class can
be accessed using the outer class name

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 21
Anonymous Inner Classes (AIC)
 They allow us to declare & instantiate a class all at
once which makes the code more concise
 They are like inner classes except that they do not
have a name
 We use them if an inner class needs to be used only
once
 AIC declaration:
new SuperClassName/InterfaceName() {
// Implement or override methods in superclass or
interface Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
22
// Other methods ifrights necessary
reserved.
Anonymous Inner Classes (cont.)
 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 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
Example: Anonymous Inner Class

AnonymousHandlerDemo Run

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 24
CS 112 Programming 2

Lecture 15
Event-Driven Programming & Animations (2)

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
Event Handling: Lambda Expressions
 Lambda expressions can be used to greatly simplify coding for
event handling
 A Lambda expression 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
Lambda Expressions: Basic Syntax
(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. For
example,
(ActionEvent e) -> { // Code for handling event e }
can be shortened as:

e -> { // Code for handling event e }


Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 27
EventHandler is a SAM Interface
 The compiler treats a lambda expression as an object
created from an anonymous inner class. Therefore, the
compiler understands that the object must be an instance of
EventHandler<ActionEvent>

 Since the EventHandler interface defines handle()


with a parameter of the ActionEvent type, the compiler
knows that e is of ActionEvent type, and the statements
in the lambda expression are all for the body of handle()

 EventHandler contains just one abstract method.


Such interfaces are known as functional or Single Abstract
Method (SAM) interfaces

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 28
Examples: Lambda Expressions

AnonymousHandlerDemo discussed a little


while back can be simplified using lambda
expressions as in LambdaHandlerDemo
LambdaHandlerDemo Run

Another example:
LoanCalculator Run

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 29
The MouseEvent Class
 A MouseEvent is fired whenever a mouse button is pressed,
released, clicked, moved, or dragged on a node or a scene
 The MouseEvent object captures the event, such as the
number of clicks, the location, or which button was pressed

MouseEventDemo Run
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 30
The KeyEvent Class
 A KeyEvent is fired whenever a key is pressed, released, or
typed on a node or a scene
 The KeyEvent object describes the nature of the event (namely,
that a key has been pressed, released, or typed) and the key
value

KeyEventDemo Run
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: ControlCircle w. Mouse & Key

ControlCircleWithMouseAndKey Run

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, for adding a listener, contains
addListener(InvalidationListener listener)
 Once the value is changed in the property, a listener is notified. The
listener class should implement the InvalidationListener
interface, which uses invalidated(Observable o) to handle
the property value change
 Every binding property is an instance of Observable
ObservablePropertyDem Run
o
DisplayResizableClock Run

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 34
Animation
Animation class and its concrete subclasses (especially
PathTransition, FadeTransition and Timeline)
provide the core functionality for all animations

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 35
PathTransition
The PathTransition class animates the moves of a node
along a path from one end to the other over a given time

PathTransitionDemo Run

FlagRisingAnimation Run
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 Run
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

TimelineDemo Run

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 38
Case Study: Clock Animation
Use the static clock from the last chapter to create a clock animation

Note: In all of our examples


so far, events have been
generated by the user. The
events for this animation,
however, are generated by
system clock

ClockAnimation Run

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

BallPane
BounceBallControl
Run

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

You might also like