Chapter - 2B - (0) Java
Chapter - 2B - (0) Java
Program:
Computer
Science
G3 – CS
Java Programming
Instructor:
Addisu M. (Asst.
Prof)
2
Ch o B
Java Programming
2
0 Properties and
Bindings
30
Graphics and
Animations
4
4
JavaFX
a new framework for developing cross-platform
rich client applns in Java
provides a wide range of features for creating
desktop, mobile, and web applns with a rich UI
fully integrated with recent versions of JRE &
Java Programming
JDK
Supports 2D and 3D graphics, audio, and video
playback.
Designed to replace Swing platform
Applns written using JavaFX library can run
consistently across multiple platforms such as
Windows, Linux, Mac, Android...
5
Architecture of JavaFX
JavaFX – has numerous built-in elements that are
interconnected with each other.
Its library comprises a valuable collection of APIs,
classes, and interfaces that are more than sufficient to
produce rich internet and GUI applications.
Java Programming
6
Architecture of JavaFX
JavaFX architecture comprises many different
components:
JavaFX API: implements all the required classes
that are capable of producing a full-featured appln
with rich graphics
Java Programming
javafx.animation: includes classes that are used
to combine transition-based animations such as
fill, fade, rotate, scale and translation, to nodes
(collection of nodes makes a scene graph).
javafx.css: comprises classes that are used to
append CSS–like styling to the JavaFX GUI applns.
javafx.geometry: contains classes that are used
to represent 2D figures and execute methods on
them.
7
Architecture of JavaFX
JavaFX architecture comprises many different
components:
javafx.application: includes a collection of
classes that are responsible for the life cycle of the
Java Programming
JavaFX appln
javafx.event: includes classes and interfaces
that are used to perform and manage events
javafx.stage: accommodates the top-level
container classes used for the JavaFX appln
Scene Graph: starting point of dev’t of any of
GUI Applns
all GUI applns are made using a Scene Graph only
8 Lifecycle of JavaFX
Application
three life cycle methods of a
JavaFX Appln class
start() – entry point method
where all code of JavaFX is to
Java Programming
be written
init() – an empty method that
can be overridden.
user cannot create stage
or scene here
stop() – an empty method
that can also be overridden.
user can write the code to
9 Lifecycle of JavaFX
Application
JavaFX appln also implements a static method
- launch()
used to launch the JavaFX appln
Java Programming
The order given in which a JavaFX appln is
launched
1. instance of the appln class is created
2. init() method is called
3. start() method is called
4. launcher waits for JavaFX appln to end and
10
Basic Structure of JavaFX
1. Extend Application
2. Override start(stage)
3. Create Nodes (e.g. Button)
Java Programming
4. Place the Nodes in Scene
5. Place the Scene on Stage
6. Show Stage
11
Basic Structure of JavaFX
Application
Unlike regular Java programs, JavaFX are not started
using main but instead using a launcher class called
Application
To create a new JavaFX appln, subclass Application
Java Programming
and override start method – will be called after
JavaFX runtime is loaded and before the appln starts
use main method to start a JavaFX application by
calling launch method (which is defined in the
Application class)
javafx.application.Application – entry point for
applns
12
Basic Structure of JavaFX
Application
JavaFX Application Class
application needs a primary launch class.
extend javafx.application.Application class
Example: subclass of Application
Java Programming
import javafx.application.Application;
public class Hello_World extends Applic
ation{
13
Basic Structure of JavaFX
Stage
javafx.stage.Stage - top level container of
the appln – usually, an OS Window
primary Stage is constructed by the platform
Java Programming
main stage is created as part of the appln
launch and it is passed as an argument in the
start method
single JavaFX appln can have multiple Stages
and use one or another
Many setter methods: setTitle(), setWidth()
use stage to set appln’s title, icon, size,
14
Basic Structure of JavaFX
Creating a Stage
create JavaFX Stage object just like any other
Java object:
Using the new command and Stage constructor.
Stage stage = new
Java Programming
Example: Stage();
Showing a Stage
Simple creating a JavaFX Stage object will not show
it. Stage stage = new
In order to make the Stage visible you must call
Stage();
either its show() or showAndWait() method
15
Basic Structure of JavaFX
Implementing start()
All subclasses of Application class must
implement the abstract start() method of the
Application class
start() method is called when JavaFX application
Java Programming
is started
Itimport
takesjavafx.application.Application;
a single parameter of type Stage
import javafx.stage.Stage;
Stage object is created for you by JavaFX runtime
public class Hello_World extends Application{
@Override
public void start(Stage primaryStage) throws Exceptio
n{
Java Programming
It calls static
importlaunch() method with command line
javafx.application.Application;
import javafx.stage.Stage;
parameters public class Hello_World extends Application{
launches the JavaFX
@Overrideruntime and your JavaFX
public void start(Stage primaryStage) throws Excep
applicationtion {
Java Programming
A stage can only show one scene at a time,
but it is possible to exchange the scene at
runtime
Scene (also called Scene Graph) is the starting
point for constructing a JavaFX appln
javafx.scene API allows the creation and
specification of several types of content
18
Basic Structure of JavaFX
Controls
built by using nodes in the scene graph
UI controls are elements that are truly
exposed to the user for intercommunication
or infn exchange.
Java Programming
response is the reaction of UI component
when some event has happened on it
package javafx.scene.control
implements all the required classes for UI
elements like Button, Label, etc
Every class describes a particular UI control
and explains few methods for their styling.
19
Basic Structure of JavaFX
Controls
can use the visually rich features of JavaFX
platform
Some of the following UI controls:
Password Field
Label Scroll Bar
Java Programming
Button Scroll Pane
Radio Button Combo Box
Checkbox ProgressBar
Choice Box Hyperlink
Text Field Menu
Toggle Button ….
20
Basic Structure of JavaFX
Adding a Scene
The previous JavaFX examples only open a
window, but nothing is displayed inside this
window
To display something inside the JavaFX
Java Programming
application window you must add a Scene to
the Stage object
This is done inside the start() method
All components to be displayed inside a
JavaFX application must be located inside a
scene
Example:
21
Basic Structure of JavaFX
Adding a Scene
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.stage.Stage;
public class Hello_World extends Application{
@Override
Java Programming
public void start(Stage primaryStage) throws Exce
ption {
Label label = new Label(“Hello World,
JavaFX!");
Scene scene = new Scene(label, 400,
200);
Java Programming
https://gluonhq.com/products/javafx/
23
Steps to Setup JavaFx
Step 2: Download recent JDK Fx file and
extract it.
Java Programming
https://www.azul.com/downloads/?package=jdk#zulu
24
Steps to Setup JavaFx
Step 3: Add
JDK Fx
platform
Tools Java
Platforms
Java Programming
Add Platform
select Java
Standard
Edition
Select the
zipped file
25
Steps to Setup JavaFx
Step 3: Add
Library
Tools Library
Add New
Library
Java Programming
26
Steps to Setup JavaFx
Step 3: Add
Library
Select the
Folder Lib
Select all files
Java Programming
Click Add
JAR/Folder
button
27
Basic Structure of JavaFX
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
Example #1
import javafx.scene.control.Button;
public class MyFirstJavaFX extends Application {
@Override // Override the start method in Application class
public void start(Stage primaryStage) {
Java Programming
// Create a button and place it in the scene
Button btOK = new Button("OK");
Scene scene = new Scene(btOK, 200, 250);
primaryStage.setScene(scene); //Place the scene in stage
primaryStage.setTitle("MyJavaFX"); // Set stage title
primaryStage.show(); // Display the stage
}
public static void main(String[] args) {
launch(args);
}
}
28
Basic Structure of JavaFX
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
Example #2
import javafx.scene.control.Button;
public class MyFirstJavaFX extends Application {
@Override
public void start(Stage primaryStage) {
Scene scene = new Scene(new Button("OK"), 200, 250);
Java Programming
primaryStage.setTitle("MyJavaFX");
primaryStage.setScene(scene);
primaryStage.show();
Stage stage = new Stage();
stage.setTitle("Second Stage");
// Set a scene with a button in the stage
stage.setScene(new Scene(new Button("New Stage"), 100,
100));
stage.show();
}
public static void main(String[] args) { launch(args); }
}
29
Basic Structure of JavaFX
Layouts
defines the way in which the components are to
be seen on the stage (position and size)
represents the structure of the UI elements on the
screen
Java Programming
All these classes belong to javafx.scene.layout
package
javafx.scene.layout.Pane class is the base class
for all built-in layout classes
E.g: HBox, VBox, FlowPane,
StackPane, TilePane,
GridPane, AnchorPane,
BorderPane, TextFlow, etc
30
Basic Structure of JavaFX
Layouts - some of the more common layouts:
Pane – base class for layout panes.
contains getChildren() method for returning a list
of nodes in pane
StackPane - put all controls in a stack (), in other
Java Programming
words, top of each other in the center of the pane
FlowPane – places nodes row-by-row horizontally
or column-by-column vertically
BorderPane - gives five areas: top, left, right,
bottom, and center
GridPane - orders controls in a 2D grid (2 row by
2 col)
HBox - orders controls in a horizontal (thus “H”)
31
Basic Structure of JavaFX
Pane & its Subclasses
Java Programming
32
Basic Structure of JavaFX
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.layout.StackPane;
import javafx.scene.control.Button;
public class ButtonInPane extends Application {
@Override // Override the start method in Application
Java Programming
class
public void start(Stage primaryStage) {
// Create a scene and place a button in the scene
StackPane pane = new StackPane();
pane.getChildren().add(new Button("OK"));
Scene scene = new Scene(pane, 200, 50);
primaryStage.setTitle("Button in a pane");
primaryStage.setScene(scene); // Place the
scene in the stage
primaryStage.show(); // Display the stage
}
33
Basic Structure of JavaFX
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.layout.GridPane;
import javafx.scene.control.*;
import javafx.geometry.*;
public class ShowGridPane extends Application {
Java Programming
@Override
public void start(Stage primaryStage) {
GridPane pane = new GridPane();
pane.setAlignment(Pos.CENTER);
pane.setHgap(5.5);
pane.setVgap(5.5);
// Place nodes in the pane at positions column, row
pane.add(new Label("First Name:"), 0, 0);
pane.add(new TextField(), 1, 0);
34
Basic Structure of JavaFX
pane.add(new Label("MI:"), 0, 1);
pane.add(new TextField(), 1, 1);
pane.add(new Label("Last Name:"), 0, 2);
pane.add(new TextField(), 1, 2);
Button btAdd = new Button("Add Name");
pane.add(btAdd, 1, 3);
GridPane.setHalignment(btAdd, HPos.RIGHT);
Java Programming
// Create a scene and place it in the stage
Scene scene = new Scene(pane);
primaryStage.setTitle("ShowGridPane");
primaryStage.setScene(scene); // Place the scene in
the stage primaryStage.show(); // Display the stage
}
public static void main(String[] args)
{ launch(args); }
}
35
Display Shapes
Any geometrical shape that can be represented
on coordinate system using two planes (X and Y)
– known as a 2D shape
Java Programming
E.g.: line, square, rectangle, circle, eclipse, &
many more
JavaFX gives the flexibility to the user to add
and create these 2D shapes in their JavaFX
36
Display Shapes
There are several classes in JavaFX API that
are used to execute 2D shapes.
All these classes are part of
javafx.scene.shape package.
class named Shape is the root class of all 2D
Java Programming
shapes
Steps to create a 2D shape are as
follows:
Step 1: instantiate the corresponding class of
the neededLine
shapeline = new
E.g., toLine();
add line, first instantiate
javafx.scene.shape.line class
37
Display Shapes
Steps to create a 2D shape are as
follows: line.setStartX(0)
Step 2: set the properties of;the required shape
using setter functions line.setStartY(0)
E.g., set X and Y coordinates
; of the starting and
Java Programming
ending point of the line like:
line.setEndX(100)
;
line.setEndY(200)
;
Step 3: add the object instantiated of the required
Group root = new Group();
shape to the group by declaring it as a parameter
root.getChildren().add(line
of the constructor.
);
E.g., add the instantiated object of line shape
38
Display Shapes
Types of 2D shapes
In javafx.scene.shape package, there are
numerous shapes available which the user
can use in their JavaFx appln
Java Programming
Line – If a user wants to create it, then they
should instantiate javafx.scene.shape.Line
class
Rectangle – If a user wants to create it,
then they should instantiate
javafx.scene.shape.Rectangle class
Ellipse – javafx.scene.shape.Ellipse class
39
Display Shapes
provides many shape classes for drawing
texts, lines, circles, rectangles, ellipses, arcs,
polygons, and polylines.
Java Programming
40
Display Shapes
Text
Java Programming
41
Display Shapes
Text import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.geometry.Insets;
Java Programming
import javafx.scene.text.Text;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import javafx.scene.text.FontPosture;
public class ShowText extends Application
{
@Override
public void start(Stage primaryStage)
{
Pane pane= new Pane();
42
Display Shapes
Text Text text1 = new Text(20, 20, "Programming
is fun");
text1.setFont(Font.font("Courier",
FontWeight.BOLD,
FontPosture.ITALIC, 15));
pane.getChildren().add(text1);
Java Programming
Text text2 = new Text(60, 60, "Programming
is fun");
pane.getChildren().add(text2);
Text text3 = new Text(10, 100, "Programming
is fun");
text3.setFill(Color.RED);
text3.setUnderline(true);
pane.getChildren().add(text3);
Scene scene= new Scene(pane, 600, 800);
43
Transformation
Defined as change in form, nature or
appearance of graphics
javafx.scene.transform represents all
transformations
contains the classes for various types of
Java Programming
transformations
Transformatio Description
n
javafx.scene.transform.Transform class –
used to change the position of the node
parent javafx.scene.transform.Translate
Translation class for all transformation classes.
class represents the
translation
used to rotate the object from its origin by a certain angle
Rotation
class javafx.scene.transform.Rotate represents the rotation
used to alter the size of the node
Scaling
class javafx.scene.transform.Scale represents Scaling
used to alter the slope of the object in a particular direction
Shearing
44
Transformation
Steps for apply transformation on the node
1. Instantiate the respective class.
E.g., to create 2D scale,Scale
Use:sc = new Scale();
2. Set the appropriate properties of the scale class
object.
Java Programming
E.g., to set the scale object properties,
scale.setX(<double value) use
setter methods: ;scale.setY(<double value)
;
scale.setPivotX(<double v
alue);
scale.setPivotY(<double v
3. Apply the transformation
alue);to the respective node.
<node-
Use object>.getTransforms().add(<Transform-
the following syntax for this purpose.
45
Transformation
Translation
change in the position of an object on the screen
position of an object gets changed by moving it
along X-Y direction
class javafx.scene.transform.Translate
Java Programming
represents the Translate transform
46
Transformation
Translation
Properties
The properties of the class along with the setter
methods are described in the following table.
Java Programming
Propert Description Setter Methods
y
represents the distance by which
setX(double
X the object is translated in X
value)
Direction.
represents the distance by which
setY(double
Y the object is translated in Y
value)
direction.
represents the distance by which
setZ(double
47
Transformation
Translation
Constructors: three constructors in the class
public Translate() : creates the new instance of
the Translate class with the default parameters.
public Translate(double X, double Y) :
Java Programming
creates the new instance with the specified (X,
Y) coordinate.
public Translate(double X, double Y, double
Z) : creates the new instance with the specified
(x,y,z) coordinate.
48
Transformation
Translation
import javafx.application.Application;
Example
import javafx.scene.*;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.scene.transform.Translate;
import javafx.stage.Stage;
Java Programming
public class TranslateExample extends Application{
@Override
public void start(Stage primaryStage) throws Exception {
//creating the Rectangles with the same coordinates
Rectangle rect1 = new Rectangle(20,20,200,150);
Rectangle rect2 = new Rectangle(20,20,200,150);
//setting rectangle properties
rect1.setFill(Color.RED);
rect1.setStroke(Color.BLACK);
rect1.setStrokeWidth(5);
rect2.setFill(Color.GREEN);
rect2.setStroke(Color.BLACK);
rect2.setStrokeWidth(5);
49
Transformation
Translation
Translate translate = new Translate();
Example
//Instantiating the Translate class
//setting the properties of the translate object
translate.setX(200);
translate.setY(200);
translate.setZ(200);
Java Programming
//applying transformation to the second rectangle
rect2.getTransforms().addAll(translate);
Java Programming
the object by a factor which is called scale factor
javafx.scene.transform.Scale class
represents scaling
transformation
51
Transformation
Scaling
Properties
Property Description Setter Methods
represents the x coordinate of the pivot setPivotX(double
pivotX
point about which the scaling is done. value)
Java Programming
represents the y coordinate of the pivot setPivotY(double
pivotY
point about which the scaling is done. value)
represents the z coordinate of the pivot setPivotZ(double
pivotZ
point about which the scaling is done. value)
represents the factor by which the object
x setX(double value)
is scaled along the X axis.
represents the factor by which the object
y setY(double value)
is scaled along the Y axis.
represents the factor by which the object
z setZ(double value)
is scaled along the Z axis.
52
Transformation
Scaling
Constructors: five constructors in the class
public Scale(): creates new instance with default
parameters
public Scale(double X, double Y): instance of
Java Programming
2D Scale.
public Scale(double X, double Y, double Z):
instance of 3D scale.
public Scale(double X, double Y, double
pivotX, double pivotY): instance of 2D scale
with specified pivot coordinates.
public Scale(double X, double Y, double Z,
53
Transformation
Scaling
import javafx.application.Application;
Example
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.scene.text.Font;
Java Programming
import javafx.scene.text.FontPosture;
import javafx.scene.text.FontWeight;
import javafx.scene.text.Text;
import javafx.scene.transform.Scale;
import javafx.stage.Stage;
public class ScaleExample extends Application{
@Override
public void start(Stage primaryStage) throws Exception {
//Creating the two circles
Circle cir1=new Circle(230,200,100);
Circle cir2=new Circle(550,200,100);
54
Transformation
Scaling
//setting the color and stroke for the circles
Example
cir1.setFill(Color.YELLOW);
cir1.setStroke(Color.BLACK);
cir2.setFill(Color.YELLOW);
cir2.setStroke(Color.BLACK);
Java Programming
// creating the text nodes for the identification
Text text1 = new Text("Original Circle");
Text text2 = new Text("Scaled with factor 1.5 in XY");
Java Programming
scale.setPivotY(200);
Java Programming
apply the animations onto the nodes.
All the classes of this package extend the class
javafx.animation.Animation.
JavaFX provides classes for the transitions like
RotateTransition, ScaleTransition,
TranslateTransition, FadeTransition,
FillTransition, StrokeTransition, etc.
57
Animation
Basic Transitions
package javafx.animation provides the classes for
performing the following transitions
Transition Description
Rotate Rotate the Node along one of the axes over the specified
Java Programming
Transition duration.
Animate the scaling of the node over the specified
Scale Transition
duration.
Translate Translate the node from one position to another over the
Transition specified duration.
Animate the opacity of the node. It keeps updating the
Fade Transition opacity of the node over a specified duration in order to
reach a target opacity value
Animate the node's fill color so that the fill color of the
Fill Transition node fluctuates between the two color values over the
specified duration.
58
Animation
Steps for applying Animations
1. Create the target node and configure its
properties.Rectangle rect = new Rectangle(120,10
0,100,100);
rect.setFill(Color.RED);
Java Programming
2. Instantiate the respective
RotateTransition transition
rotate = new class
RotateTransition();
Java Programming
RotateTransition is represented by the class
javafx.animation.RotateTransition.
Properties
The properties of the class along with their
setter methods are described in the following
table.
60
Animation
Rotate Transition
Properties
properties
Property of
Description the class along with their
Setter setter
Methods
axis methods are
represents thedescribed
axis of rotate in the following
transition. table.
setAxis(Point3D value)
Java Programming
represents the angle by which the setByAngle(double
byAngle
object will be rotated. value)
represents the duration of the rotate setDuration(Duration
duration
transition. value)
represents the start Angle of the rotate setFromAngle(double
fromAngle
transition. value)
represents the node on which the
node setNode(Node value)
rotate transition to be applied.
represents the stop angle value for the setToAngle(double
toAngle
rotate transition. value)
61
Animation
Rotate Transition
Constructors: three constructors in the class
public RotateTransition() : creates the new
instance of RotateTransition with the default
parameters.
Java Programming
public RotateTransition(Duration duration) :
Creates new instance of RotateTransition with the
specified duration value
public RotateTransition(Duration duration,
Node node): creates the new instance of
RotateTransition with the specified duration value
and Node on which, it is applied.
62
Animation
Rotate Transition
import javafx.animation.RotateTransition;
Example
import javafx.application.Application;
import javafx.geometry.Point3D;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.paint.Color;
Java Programming
import javafx.scene.shape.Rectangle;
import javafx.scene.transform.Rotate;
import javafx.stage.Stage;
import javafx.util.Duration;
public class Rotate_Transition extends Application{
@Override
public void start(Stage primaryStage) throws Exception {
//Creating Rectangle
Rectangle rect = new Rectangle(200,100,200,200);
rect.setFill(Color.LIMEGREEN);
rect.setStroke(Color.HOTPINK);
rect.setStrokeWidth(5);
63
Animation
Rotate Transition
//Instantiating RotateTransition class
Example
RotateTransition rotate = new RotateTransition();
Java Programming
// setting the angle of rotation
rotate.setByAngle(360);
rotate.setNode(rect);
Java Programming
rotate.play();
Java Programming
class javafx.animation.ScaleTransition.
Properties
The properties of the class along with their
setter methods are described in the following
table.
66
Animation
Scale Transition
Properties
Property Description Setter Methods
represents the incremented stop X factor
byX setByX(double value)
value.
represents the incremented stop Y factor
Java Programming
byY setByY(double value)
value.
represents the incremented stop Z factor
byZ setByZ(double value)
value.
setDuration(Duration
duration represents the duration of scale transition.
value)
represents the start X value of
fromX setFromX(double value)
ScaleTransition.
represents the start Y value of
fromY setFromY(double value)
ScaleTransition.
represents onto which, the scale transition is
node setNode(Node node)
applied.
67
Animation
Scale Transition
Constructors: three constructors in the class
public TranslateTransition() : creates the new
instance of TranslateTransition with the default
parameters.
Java Programming
public TranslateTransition(Duration
duration) : creates the new instance of
TranslateTransition with the specified duration.
public TranslateTransition(Duration
duration, Node node) : creates the new
instance of Translate Transition with the specified
duration and node.
68
Animation
Scale Transition
import javafx.animation.TranslateTransition;
Example
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
Java Programming
import javafx.stage.Stage;
import javafx.util.Duration;
public class Translate_Transition extends Application{
@Override
public void start(Stage primaryStage) throws Exception {
//Creating the circle
Circle cir = new Circle(50,100,50);
Java Programming
//setting the duration for the Translate transition
translate.setDuration(Duration.millis(1000));
//
the transition will set to be auto reversed by setting this to true
translate.setAutoReverse(true);
//
setting Circle as the node onto which the transition will be applied
70
Animation
Scale Transition
//playing the transition
Example
translate.play();
Java Programming
Scene scene = new Scene(root,500,200,Color.WHEAT);
primaryStage.setScene(scene);
primaryStage.setTitle("Translate Transition example");
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
71
Event Handling
JavaFX provides the flexibility to create various
types of applications such as Desktop, Web and
graphical applications
user may need to interact with appln in most of the
cases.
Java Programming
An event is occurred whenever the user interacts
with the application nodes.
There are various sources by which user can
generate event
E.g., User can make use of mouse or can press
any key on or can scroll any page of the appln
events are basically the notifications that tell that
72
Event Handling
Types of Events
1. Foreground Events
mainly occurred due to the direct
interaction of the user with the GUI of the
appln.
Java Programming
E.g., clicking the button, pressing a key,
selecting an item from the list, scrolling the
page, etc.
2. Background Events
doesn't require user's interaction with the
appln.
mainly occurred to the OS interrupts,
73
Event Handling
Processing Events
events are basically used to notify the appln
about the actions taken by the user.
JavaFX provides the mechanism to capture
Java Programming
the events, route to its target and letting
appln handle the events
javafx.event.Event class contains all
subclasses representing types of Events that
can be generated
Any event is an instance of the class Event
or any of its subclasses
There are various events in JavaFX i.e.
74
Event Handling
Processing Events
properties of an event is described in ff table
Property Description
It is the type of the event that is being generated. It is
Java Programming
basically the instance of EventType class. It is
hierarchical. The instance of EventType class is further
Event Type
classified into various type of events for example
KeyEvent class contains KEY_PRESSED, KEY_RELEASED,
and KEY_TYPED types.
It represents source of the event i.e. the origin which is
Source
responsible to generate the event.
It is the node on which the event is generated. It remains
unchanged for the generated event. It is the instance of
Target
any of the class that implements the EventTarget
interface.
75
Event Handling
Event Delivery Process
ff steps need to be followed in order to
handle events
1. Route Construction
An Event Dispatch Chain is created in order
Java Programming
to determine the default route of the event,
whenever it is generated. The Event dispatch
chain contains the path from the stage to the
Node on which the event is generated.
An event dispatch chain is created in the
following image for the event generated on
one of the scene graph node.
76
Event Handling
Event Delivery Process
1. Route Construction
Java Programming
77
Event Handling
Event Delivery Process
2. Event Capturing Phase
Once the Event Dispatch Chain is created, the event
is dispatched from the source node of the event. All
the nodes are traversed by the event from top to
Java Programming
bottom. If the event filter is registered with any of
these nodes, then it will be executed. If any of the
nodes are not registered with the event filter then
the event is transferred to the target node. The
target node processes the event in that case.
78
Event Handling
Event Delivery Process
3. Event Bubbling
Once the event is processed by the target node or
by any of the registered filter, the event traverses all
the nodes again from the bottom to the stage node.
Java Programming
If any of these nodes are registered with the event
filter, then it will get executed otherwise the process
gets completed
4. Event Handlers and Filters
Event Handlers and filters contains application logic
to process an event. A node can be registered to
more than one Event Filters. The interface
javafx.event.EventHandler must be implemented by
all the event handlers and filters.
79
Event Handling
Event Handlers
JavaFX facilitates to use Event Handlers to
handle events generated by Keyboard Actions,
Mouse Actions, and many more source nodes.
Event Handlers – used to handle the events in
Java Programming
the Event bubbling phase
There can be more than one Event handlers for a
single node.
We can also use single handler for more than one
node and more than one event type.
80
Event Handling
Adding an Event Handler
Event Handler must be registered for a node in
order to process the events in the event bubbling
phase.
Event handler is the implementation of the
Java Programming
EventHandler interface.
The handle() method of the interface contains
the logic which is executed when the event is
triggered.
To register the EventHandler, addEventHandler()
is used. In this method, two arguments are
passed. One is event type and the other is
81
Event Handling
Adding an Event Handler
node.addEventHandler(<EventType>,
Java Programming
new EventHandler<Event-Type>()
{
public void handle(<EventType> e)
{
//handling code
}
});
82
Event Handling
import javafx.animation.TranslateTransition;
import javafx.application.Application;
Example
import javafx.event.EventHandler;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.input.MouseEvent;
Java Programming
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.stage.Stage;
import javafx.util.Duration;
public class JavaFX_EventHandler extends Application{
@Override
public void start(Stage primaryStage) throws Exception {
//Creating Circle and setting the color and stroke in the circle
Circle c = new Circle(100,100,50);
c.setFill(Color.GREEN);
c.setStroke(Color.BLACK);
83
Event Handling
//creating play button and setting coordinates for the button
Button btn = new Button("Play"); Example
btn.setTranslateX(125);
btn.setTranslateY(200);
// creating pause button and setting coordinate for the pause button
Button btn1 = new Button("Pause");
Java Programming
btn1.setTranslateX(175);
btn1.setTranslateY(200);
@Override
public void handle(MouseEvent event) {
if(event.getSource()==btn) {
trans.play(); //animation will be played when the play button is clicked
Java Programming
}
if(event.getSource()==btn1) {
trans.pause(); //animation will be paused when the pause button is clicked
}
event.consume();
}
};
Java Programming
}
public static void main(String[] args) {
launch(args);
}
}
86
Event Handling
Example
Java Programming
87
Event Handling
Removing EventHandler
when we no longer need an EventHandler to
process the events for a node or event types, we
can remove the EventHandler by using the method
Java Programming
removeEventHandler() method. This method takes
two arguments, event type and EventHandler
Object.
node.removeEventHandler(<EventType>,handler);
THANKS
!
Questions,
Ambiguities,
Doubts, … ???