SlideShare une entreprise Scribd logo
1  sur  44
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved.
1
Chapter 15 Event-Driven
Programming and Animations
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved.
2
Motivations
Suppose you want to write a GUI
program that lets the user enter a
course grade, and hours for three
courses and click the Calculate
button to obtain the GPA. How do
you accomplish the task? You have
to use event-driven programming
to write the code to respond to the
button-clicking event.
GpaCalculator Run
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 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 GPA 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, Eleventh Edition, (c) 2017 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.
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved.
5
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) 2017 Pearson Education, Inc. All
rights reserved.
6
6
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) 2017 Pearson Education, Inc. All
rights reserved.
7
7
Trace Execution
public class HandleEvent extends Application {
public void start(Stage primaryStage) {
…
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");
}
}
1. Start from the
main method to
create a window and
display it
animation
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved.
8
8
Trace Execution
public class HandleEvent extends Application {
public void start(Stage primaryStage) {
…
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");
}
}
animation
2. Click OK
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved.
9
9
Trace Execution
public class HandleEvent extends Application {
public void start(Stage primaryStage) {
…
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");
}
}
animation
3. The JVM invokes
the listener’s handle
method
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved.
10
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) 2017 Pearson Education, Inc. All
rights reserved.
11
Event Classes event ‫انواع‬
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved.
12
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) 2017 Pearson Education, Inc. All
rights reserved.
13
Selected User Actions and Handlers
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved.
14
The Delegation Model
‫هذا‬ ‫فيه‬ ‫حيسالنا‬ ‫مش‬
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved.
15
The Delegation Model: Example
Button btOK = new Button("OK");
OKHandlerClass handler = new OKHandlerClass();
btOK.setOnAction(handler);
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved.
16
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) 2017 Pearson Education, Inc. All
rights reserved.
17
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) 2017 Pearson Education, Inc. All
rights reserved.
18
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) 2017 Pearson Education, Inc. All
rights reserved.
19
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) 2017 Pearson Education, Inc. All
rights reserved.
20
Inner Classes, cont.
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved.
21
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) 2017 Pearson Education, Inc. All
rights reserved.
22
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, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved.
23
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) 2017 Pearson Education, Inc. All
rights reserved.
24
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) 2017 Pearson Education, Inc. All
rights reserved.
25
Anonymous Inner Classes (cont.)
AnonymousHandlerDemo Run
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved.
26
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(
new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent e) {
// Code for processing event e
}
}
});
(a) Anonymous inner class event handler
btEnlarge.setOnAction(e -> {
// Code for processing event e
});
(b) Lambda expression event handler
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved.
27
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) 2017 Pearson Education, Inc. All
rights reserved.
28
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 Run
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved.
29
Problem: GPA Calculator
GpaCalculator Run
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved.
30
The MouseEvent Class
MouseEventDemo Run
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved.
The MouseEvent
 Four constants— PRIMARY ,
SECONDARY , MIDDLE , and NONE —
are defined in MouseButton to indicate the
left, right, middle, and none mouse buttons,
respectively. You can use the getButton()
method to detect which button is pressed.
 For example, getButton() ==
MouseButton.SECONDARY tests if the
right button was pressed. You can also use
the isPrimaryButtonDown(),
isSecondaryButtonDown(), and
isMiddleButtonDown() to test if the primary
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved.
32
The KeyEvent Class
KeyEventDemo Run
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved.
KeyEvent
 The key pressed handler is invoked when a
key is pressed.
 The key released handler is invoked when a
key is released,
 The key typed handler is invoked when a
Unicode character is entered.
 If a key does not have a Unicode (e.g.,
function keys, modifier keys, action keys,
arrow keys, and control keys), the key typed
handler will not be invoked.
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved.
KeyEvent
 Every key event has an associated code that
is returned by the getCode() method in
KeyEvent.
 For the key-pressed and key-released
events, getCode() returns the value as
defined in the table, getText() returns a
string that describes the key code, and
getCharacter() returns an empty string.
 For the key-typed event, getCode() returns
UNDEFINED and getCharacter() returns
the Unicode character or a sequence of
characters associated with the key-typed
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved.
35
The KeyCode Constants
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved.
Focus
 Only a focused node can receive KeyEvent .
 Invoking requestFocus() on text enables text
to receive key input.
 This method must be invoked after the stage
is displayed.
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved.
37
Example: Control Circle with Mouse
and Key
ControlCircleWithMouseAndKey Run
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved.
38
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 Run
DisplayResizableClock Run
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved.
39
Animation
JavaFX provides the Animation class with the core
functionality for all animations.
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved.
40
PathTransition
FlagRisingAnimation Run
PathTransitionDemo Run
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved.
41
FadeTransition
The FadeTransition class animates the change of the
opacity in a node over a given time.
FadeTransitionDemo Run
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved.
42
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 Run
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved.
43
Clock Animation
ClockAnimation Run
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved.
44
Case Study: Bouncing Ball
BounceBallControl
BallPane Run

Contenu connexe

Similaire à Visual programming.ppt

Advance Java Programming(CM5I) Event handling
Advance Java Programming(CM5I) Event handlingAdvance Java Programming(CM5I) Event handling
Advance Java Programming(CM5I) Event handlingPayal Dungarwal
 
C# .NET: Language Features and Creating .NET Projects, Namespaces Classes and...
C# .NET: Language Features and Creating .NET Projects, Namespaces Classes and...C# .NET: Language Features and Creating .NET Projects, Namespaces Classes and...
C# .NET: Language Features and Creating .NET Projects, Namespaces Classes and...yazad dumasia
 
21UCAC31 Java Programming.pdf(MTNC)(BCA)
21UCAC31 Java Programming.pdf(MTNC)(BCA)21UCAC31 Java Programming.pdf(MTNC)(BCA)
21UCAC31 Java Programming.pdf(MTNC)(BCA)ssuser7f90ae
 
9781111530532 ppt ch06
9781111530532 ppt ch069781111530532 ppt ch06
9781111530532 ppt ch06Terry Yoast
 
9781111530532 ppt ch06
9781111530532 ppt ch069781111530532 ppt ch06
9781111530532 ppt ch06Terry Yoast
 
Introduction to Software Development
Introduction to Software DevelopmentIntroduction to Software Development
Introduction to Software DevelopmentZeeshan MIrza
 
I assignmnt(oops)
I assignmnt(oops)I assignmnt(oops)
I assignmnt(oops)Jay Patel
 
JEDI Slides-Intro2-Chapter20-GUI Event Handling.pdf
JEDI Slides-Intro2-Chapter20-GUI Event Handling.pdfJEDI Slides-Intro2-Chapter20-GUI Event Handling.pdf
JEDI Slides-Intro2-Chapter20-GUI Event Handling.pdfMarlouFelixIIICunana
 
Guice tutorial
Guice tutorialGuice tutorial
Guice tutorialAnh Quân
 
28-GUI application.pptx.pdf
28-GUI application.pptx.pdf28-GUI application.pptx.pdf
28-GUI application.pptx.pdfNguynThiThanhTho
 
Ch12. graphical user interfaces
Ch12. graphical user interfacesCh12. graphical user interfaces
Ch12. graphical user interfacesArslan Karamat
 
02slidLarge value of face area Large value of face area
02slidLarge value of face area Large value of face area02slidLarge value of face area Large value of face area
02slidLarge value of face area Large value of face areaAhmadHashlamon
 
12slide.ppt
12slide.ppt12slide.ppt
12slide.pptmohaz5
 
Chapter 1_Intro to Java.ppt
Chapter 1_Intro to Java.pptChapter 1_Intro to Java.ppt
Chapter 1_Intro to Java.pptLisaMalar
 
Chapter11 graphical components
Chapter11 graphical componentsChapter11 graphical components
Chapter11 graphical componentsArifa Fatima
 

Similaire à Visual programming.ppt (20)

Advance Java Programming(CM5I) Event handling
Advance Java Programming(CM5I) Event handlingAdvance Java Programming(CM5I) Event handling
Advance Java Programming(CM5I) Event handling
 
C# .NET: Language Features and Creating .NET Projects, Namespaces Classes and...
C# .NET: Language Features and Creating .NET Projects, Namespaces Classes and...C# .NET: Language Features and Creating .NET Projects, Namespaces Classes and...
C# .NET: Language Features and Creating .NET Projects, Namespaces Classes and...
 
21UCAC31 Java Programming.pdf(MTNC)(BCA)
21UCAC31 Java Programming.pdf(MTNC)(BCA)21UCAC31 Java Programming.pdf(MTNC)(BCA)
21UCAC31 Java Programming.pdf(MTNC)(BCA)
 
9781111530532 ppt ch06
9781111530532 ppt ch069781111530532 ppt ch06
9781111530532 ppt ch06
 
9781111530532 ppt ch06
9781111530532 ppt ch069781111530532 ppt ch06
9781111530532 ppt ch06
 
Introduction to Software Development
Introduction to Software DevelopmentIntroduction to Software Development
Introduction to Software Development
 
Oopp Lab Work
Oopp Lab WorkOopp Lab Work
Oopp Lab Work
 
I assignmnt(oops)
I assignmnt(oops)I assignmnt(oops)
I assignmnt(oops)
 
JEDI Slides-Intro2-Chapter20-GUI Event Handling.pdf
JEDI Slides-Intro2-Chapter20-GUI Event Handling.pdfJEDI Slides-Intro2-Chapter20-GUI Event Handling.pdf
JEDI Slides-Intro2-Chapter20-GUI Event Handling.pdf
 
Google GIN
Google GINGoogle GIN
Google GIN
 
Guice tutorial
Guice tutorialGuice tutorial
Guice tutorial
 
GUI JAVA PROG ~hmftj
GUI  JAVA PROG ~hmftjGUI  JAVA PROG ~hmftj
GUI JAVA PROG ~hmftj
 
28-GUI application.pptx.pdf
28-GUI application.pptx.pdf28-GUI application.pptx.pdf
28-GUI application.pptx.pdf
 
Ch12. graphical user interfaces
Ch12. graphical user interfacesCh12. graphical user interfaces
Ch12. graphical user interfaces
 
02slidLarge value of face area Large value of face area
02slidLarge value of face area Large value of face area02slidLarge value of face area Large value of face area
02slidLarge value of face area Large value of face area
 
Csharp
CsharpCsharp
Csharp
 
12slide.ppt
12slide.ppt12slide.ppt
12slide.ppt
 
Chapter 1_Intro to Java.ppt
Chapter 1_Intro to Java.pptChapter 1_Intro to Java.ppt
Chapter 1_Intro to Java.ppt
 
Chapter11 graphical components
Chapter11 graphical componentsChapter11 graphical components
Chapter11 graphical components
 
DS Unit 6.ppt
DS Unit 6.pptDS Unit 6.ppt
DS Unit 6.ppt
 

Dernier

Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Steffen Staab
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsAndolasoft Inc
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsJhone kinadey
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️Delhi Call girls
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceCALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceanilsa9823
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️anilsa9823
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AIABDERRAOUF MEHENNI
 

Dernier (20)

Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceCALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
 

Visual programming.ppt

  • 1. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All rights reserved. 1 Chapter 15 Event-Driven Programming and Animations
  • 2. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All rights reserved. 2 Motivations Suppose you want to write a GUI program that lets the user enter a course grade, and hours for three courses and click the Calculate button to obtain the GPA. How do you accomplish the task? You have to use event-driven programming to write the code to respond to the button-clicking event. GpaCalculator Run
  • 3. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 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 GPA 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).
  • 4. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 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.
  • 5. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All rights reserved. 5 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
  • 6. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All rights reserved. 6 6 Handling GUI Events Source object (e.g., button) Listener object contains a method for processing the event.
  • 7. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All rights reserved. 7 7 Trace Execution public class HandleEvent extends Application { public void start(Stage primaryStage) { … 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"); } } 1. Start from the main method to create a window and display it animation
  • 8. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All rights reserved. 8 8 Trace Execution public class HandleEvent extends Application { public void start(Stage primaryStage) { … 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"); } } animation 2. Click OK
  • 9. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All rights reserved. 9 9 Trace Execution public class HandleEvent extends Application { public void start(Stage primaryStage) { … 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"); } } animation 3. The JVM invokes the listener’s handle method
  • 10. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All rights reserved. 10 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.
  • 11. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All rights reserved. 11 Event Classes event ‫انواع‬
  • 12. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All rights reserved. 12 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.
  • 13. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All rights reserved. 13 Selected User Actions and Handlers
  • 14. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All rights reserved. 14 The Delegation Model ‫هذا‬ ‫فيه‬ ‫حيسالنا‬ ‫مش‬
  • 15. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All rights reserved. 15 The Delegation Model: Example Button btOK = new Button("OK"); OKHandlerClass handler = new OKHandlerClass(); btOK.setOnAction(handler);
  • 16. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All rights reserved. 16 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
  • 17. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All rights reserved. 17 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
  • 18. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All rights reserved. 18 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.
  • 19. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All rights reserved. 19 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
  • 20. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All rights reserved. 20 Inner Classes, cont.
  • 21. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All rights reserved. 21 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.
  • 22. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All rights reserved. 22 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
  • 23. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All rights reserved. 23 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.
  • 24. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All rights reserved. 24 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 }
  • 25. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All rights reserved. 25 Anonymous Inner Classes (cont.) AnonymousHandlerDemo Run
  • 26. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All rights reserved. 26 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( new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent e) { // Code for processing event e } } }); (a) Anonymous inner class event handler btEnlarge.setOnAction(e -> { // Code for processing event e }); (b) Lambda expression event handler
  • 27. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All rights reserved. 27 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.
  • 28. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All rights reserved. 28 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 Run
  • 29. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All rights reserved. 29 Problem: GPA Calculator GpaCalculator Run
  • 30. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All rights reserved. 30 The MouseEvent Class MouseEventDemo Run
  • 31. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All rights reserved. The MouseEvent  Four constants— PRIMARY , SECONDARY , MIDDLE , and NONE — are defined in MouseButton to indicate the left, right, middle, and none mouse buttons, respectively. You can use the getButton() method to detect which button is pressed.  For example, getButton() == MouseButton.SECONDARY tests if the right button was pressed. You can also use the isPrimaryButtonDown(), isSecondaryButtonDown(), and isMiddleButtonDown() to test if the primary
  • 32. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All rights reserved. 32 The KeyEvent Class KeyEventDemo Run
  • 33. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All rights reserved. KeyEvent  The key pressed handler is invoked when a key is pressed.  The key released handler is invoked when a key is released,  The key typed handler is invoked when a Unicode character is entered.  If a key does not have a Unicode (e.g., function keys, modifier keys, action keys, arrow keys, and control keys), the key typed handler will not be invoked.
  • 34. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All rights reserved. KeyEvent  Every key event has an associated code that is returned by the getCode() method in KeyEvent.  For the key-pressed and key-released events, getCode() returns the value as defined in the table, getText() returns a string that describes the key code, and getCharacter() returns an empty string.  For the key-typed event, getCode() returns UNDEFINED and getCharacter() returns the Unicode character or a sequence of characters associated with the key-typed
  • 35. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All rights reserved. 35 The KeyCode Constants
  • 36. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All rights reserved. Focus  Only a focused node can receive KeyEvent .  Invoking requestFocus() on text enables text to receive key input.  This method must be invoked after the stage is displayed.
  • 37. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All rights reserved. 37 Example: Control Circle with Mouse and Key ControlCircleWithMouseAndKey Run
  • 38. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All rights reserved. 38 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 Run DisplayResizableClock Run
  • 39. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All rights reserved. 39 Animation JavaFX provides the Animation class with the core functionality for all animations.
  • 40. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All rights reserved. 40 PathTransition FlagRisingAnimation Run PathTransitionDemo Run
  • 41. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All rights reserved. 41 FadeTransition The FadeTransition class animates the change of the opacity in a node over a given time. FadeTransitionDemo Run
  • 42. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All rights reserved. 42 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 Run
  • 43. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All rights reserved. 43 Clock Animation ClockAnimation Run
  • 44. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All rights reserved. 44 Case Study: Bouncing Ball BounceBallControl BallPane Run