Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
28 views

Unit-7 - JAVAFX basics & Event-driven Programming & Animations

The document provides an overview of JavaFX, a Java library for building Rich Internet Applications and Desktop Applications, detailing its architecture, application structure, and lifecycle. It highlights the features of JavaFX, including its ability to create 2D shapes, manage events, and utilize animations. Additionally, it outlines the steps to create a JavaFX application and provides examples of basic shapes and their implementation.

Uploaded by

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

Unit-7 - JAVAFX basics & Event-driven Programming & Animations

The document provides an overview of JavaFX, a Java library for building Rich Internet Applications and Desktop Applications, detailing its architecture, application structure, and lifecycle. It highlights the features of JavaFX, including its ability to create 2D shapes, manage events, and utilize animations. Additionally, it outlines the steps to create a JavaFX application and provides examples of basic shapes and their implementation.

Uploaded by

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

Object Oriented Programming -I (3140705)

Unit-07
JavaFX and Event-
driven programming
and animations
 Outline
Looping

 What is JavaFX?
 Architecture of JavaFX API
 JavaFX Application Structure
 Lifecycle of JavaFX Application
 2D Shape
 JavaFX - Colors
 JavaFX – Image
 Layout Panes
 JavaFX – Events
 Property Binding
 Animation
What is JavaFX?
 JavaFX is a Java library used to build Rich Internet Applications (RIA) and Desktop
Applications.
 The applications developed using JavaFX can run on various devices such as Desktop
Computers, Mobile Phones, TVs, Tablets, etc.
 To develop GUI Applications using Java programming language, the programmers rely on
libraries such as Advanced Windowing Toolkit (AWT) and Swing. After the advent of JavaFX,
these Java programmers can now develop GUI applications effectively with rich content.
 Why we need JavaFX
 To develop Client Side Applications with rich features, the programmers used to depend on various libraries
to add features such as Media, UI controls, Web, 2D and 3D, etc.
 JavaFX provides a rich set of graphics and media API’s and it leverages the modern Graphical Processing
Unit through hardware accelerated graphics.
 One can use JavaFX with JVM based technologies such as Java, Groovy and JRuby. If developers opt for
JavaFX, there is no need to learn additional technologies.

#3140705 (OOP-I)  Unit 07 – JavaFX basics 3


Features of JavaFX
 Written in Java
 FXML
 Scene Builder
 Swing Interoperability
 Built-in UI controls
 CSS like Styling
 Canvas and Printing API
 Rich set of API’s
 Integrated Graphics library
 Graphics pipeline

#3140705 (OOP-I)  Unit 07 – JavaFX basics 4


Architecture of JavaFX API

JavaFX API Scene Graph

Quantum Toolkit

JavaFX Graphics Engine


Prism Glass Web View Media

Win32 | GWT OpenGL | D3D Web kit G Streams

JDK API and Toolkit

Java Virtual Machine

#3140705 (OOP-I)  Unit 07 – JavaFX basics 5


Architecture of JavaFX API (Cont.)
 Scene Graph
 A Scene Graph is the starting point of the construction of the GUI Application. It holds the (GUI) application
primitives that are termed as nodes.
 A node is a visual/graphical object and it may include
 Geometrical (Graphical) objects
 UI controls
 Containers
 Media elements
 Prism
 Prism is a high performance hardware–accelerated graphical pipeline that is used to render the graphics in
JavaFX. It can render both 2-D and 3-D graphics.
 GWT (Glass Windowing Toolkit)
 GWT provides services to manage Windows, Timers, Surfaces and Event Queues.
 GWT connects the JavaFX Platform to the Native Operating System.

#3140705 (OOP-I)  Unit 07 – JavaFX basics 6


Architecture of JavaFX API (Cont.)
 Quantum Toolkit
 It is an abstraction over the low-level components of Prism, Glass, Media Engine, and Web Engine. It ties
Prism and GWT together and makes them available to JavaFX.
 WebView
 WebView is the component of JavaFX which is used to process HTML content. It uses a technology called
Web Kit, which is an internal open-source web browser engine. This component supports different web
technologies like HTML5, CSS, JavaScript, DOM and SVG.
 Media Engine
 The JavaFX media engine is based on an open-source engine known as a Streamer. This media engine
supports the playback of video and audio content.

#3140705 (OOP-I)  Unit 07 – JavaFX basics 7


Installing JavaFX
 You can install JavaFX directly on eclipse using the
Market Place.
 To download JavaFX from Market Place, open
Help -> Eclipse Market Place
 Then simply search “fx” and install the e(fx)clipse from
the Market Place.
 It will take time to install and after installation you need
to restart the eclipse.
 Alternatively you can also download JavaFX SDK
manually from https://gluonhq.com/products/javafx/
 Then you need to create a custom library in eclipse to
load JavaFX to your project.

#3140705 (OOP-I)  Unit 07 – JavaFX basics 8


JavaFX Application Structure

Stage
Scene
Scene Graph
Root
Node

Branch Leaf
Node Node

Leaf Leaf
Node Node

#3140705 (OOP-I)  Unit 07 – JavaFX basics 9


Stage
 A stage (a window) contains all the objects of a JavaFX application.
 It is represented by Stage class of the package javafx.stage.
 The primary stage is created by the platform itself. The created stage object is passed as an
argument to the start() method of the Application class.
 A stage has two parameters determining its position namely Width and Height.
 There are five types of stages available
 Decorated // stageObj.initStyle(StageStyle.DECORATED);
 Undecorated // stageObj.initStyle(StageStyle.UNDECORATED);
 Transparent // stageObj.initStyle(StageStyle.TRANSPARENT);
 Unified // stageObj.initStyle(StageStyle.UNIFIED);
 Utility // stageObj.initStyle(StageStyle.UTILITY);
 You have to call the show() method to display the contents of a stage.

#3140705 (OOP-I)  Unit 07 – JavaFX basics 10


Scene
 A scene represents the physical contents of a JavaFX application. It contains all the contents
of a scene graph.
 The class Scene of the package javafx.scene represents the scene object. At an instance,
the scene object is added to only one stage.
 You can create a scene by instantiating the Scene Class.
 You can opt for the size of the scene by passing its dimensions (height and width) along with
the root node to its constructor.

#3140705 (OOP-I)  Unit 07 – JavaFX basics 11


Scene Graph and Nodes
 A scene graph is a tree-like data structure (hierarchical) representing the contents of a scene.
In contrast, a node is a visual/graphical object of a scene graph. A node may include,
 Geometrical (Graphical) objects (2D and 3D) such as − Circle, Rectangle, Polygon, etc.
 UI Controls − Button, Checkbox, Choice Box, Text Area, etc.
 Containers (Layout Panes) – Border Pane, Grid Pane, Flow Pane, etc.
 Media elements – Audio, Video and Image Objects.
 The Node class of the package javafx.scene represents a node in JavaFX, this class is the
super class of all the nodes.
 Root Node − First Scene Graph is known as Root node. It’s mandatory to pass root node to the scene graph.
 Branch Node/Parent Node − The node with child nodes are known as branch/parent nodes. The abstract
class named Parent of the package javafx.scene is the base class of all the parent nodes, and those
parent nodes will be of the following types
 Group − A group node is a collective node that contains a list of children nodes.
 Region − It is the base class of all the JavaFX Node based UI Controls, such as Chart, Pane and Control.
 WebView − This node manages the web engine and displays its contents.
 Leaf Node − The node without child nodes is known as the leaf node. For example, Rectangle, Ellipse, Box,
ImageView, MediaView are examples of leaf nodes.
#3140705 (OOP-I)  Unit 07 – JavaFX basics 12
Steps to create JavaFX application
1. Extend the Application class of javafx.application package in your class.
2. Override start method of Application class.
3. Prepare a scene graph with the required nodes.
4. Prepare a Scene with the required dimensions and add the scene graph (root node of the
scene graph) to it.
5. Prepare a stage and add the scene to the stage and display the contents of the stage.

#3140705 (OOP-I)  Unit 07 – JavaFX basics 13


3. Prepare a Scene graph
 Since the root node is the first node, you need to create a root node and it can be chosen from
the Group, Region or WebView.
 Group
A Group node is represented by the class named Group which belongs to the package javafx.scene,
you can create a Group node by instantiating this class as shown below.
Group root = new Group();
Group root = new Group(NodeObject);
 Region
It is the Base class of all the JavaFX Node-based UI Controls, such as −
 Chart − This class is the base class of all the charts and it belongs to the package javafx.scene.chart
which embeds charts in application.
 Pane − A Pane is the base class of all the layout panes such as AnchorPane, BorderPane, DialogPane, etc. This
class belong to a package that is called as − javafx.scene.layout which inserts predefined layouts in your
application.
 Control − It is the base class of the User Interface controls such as Accordion, ButtonBar, ChoiceBox,
ComboBoxBase, HTMLEditor, etc. This class belongs to the package javafx.scene.control.
 WebView
This node manages the web engine and displays its contents.
#3140705 (OOP-I)  Unit 07 – JavaFX basics 14
4. Preparing the Scene
 A JavaFX scene is represented by the Scene class of the package javafx.scene.
Scene scene = new Scene(root,width,heigth);
 While instantiating, it is mandatory to pass the root object to the constructor of the Scene
class whereas width and height of the scene are optional parameters to the constructor.

#3140705 (OOP-I)  Unit 07 – JavaFX basics 15


5. Preparing the Stage
 Stage is the container of any JavaFX application and it provides a window for the application. It
is represented by the Stage class of the package javafx.stage.
 An object of this class is passed as a parameter of the start() method of the Application
class.
 Using this object, various operations on the stage can be performed like
 Set the title for the stage using the method setTitle().
primaryStage.setTitle("Sample application");
 Attach the scene object to the stage using the setScene() method.
primaryStage.setScene(scene);
 Display the contents of the scene using the show() method as shown below.
primaryStage.show();

#3140705 (OOP-I)  Unit 07 – JavaFX basics 16


Basic Example of JavaFX
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.paint.Color;
import javafx.stage.Stage;

public class MyFirstGUI extends Application{


public void start(Stage primaryStage) throws Exception{ Create Scene Graph
Group root = new Group(); using Group, Region or
Scene s = new Scene(root,600,400); WebView
primaryStage.setTitle("My First User Interface");
Create Scene by adding
s.setFill(Color.ORANGE);
Group (root) to it along
primaryStage.setScene(s);
with its width and height
primaryStage.show();
} Set the scene to the stage object
(primaryStage) which is passed as an
public static void main(String[] args) { argument to start() using setScene() method
launch(args);
}
}

#3140705 (OOP-I)  Unit 07 – JavaFX basics 17


Lifecycle of JavaFX Application
 The JavaFX Application class has three life cycle methods.
init() − An empty method which can be overridden, stage or scene cannot be created in
this method.
start() − The entry point method where the JavaFX graphics code is to be written.
stop() − An empty method which can be overridden, here the logic to stop the application is
written.
 It also provides a static method named launch() to launch JavaFX application. This method
is called from static content only mainly in main method.
 Whenever a JavaFX application is launched, the following actions will be carried out (in the
same order).
 An instance of the application class is created.
 init() method is called.
 start() method is called.
 The launcher waits for the application to finish and calls the stop() method.

#3140705 (OOP-I)  Unit 07 – JavaFX basics 18


2D Shape
 2D shape is a geometrical figure that can be drawn on the XY plane like Line, Rectangle, Circle,
etc.
 Using the JavaFX library, you can draw −
 Predefined shapes – Line, Rectangle, Circle, Ellipse, Polygon, Polyline, Cubic Curve, Quad Curve, Arc.
 2D shape by parsing SVG path.
 Each of the above mentioned 2D shape is represented by a class which belongs to the package
javafx.scene.shape. The class named Shape is the base class of all the 2-Dimensional
shapes in JavaFX.

#3140705 (OOP-I)  Unit 07 – JavaFX basics 19


Classes for Shape (javafx.scene.shape)
Shape Class Example
Line Line Line line = new Line();
line.setStartX(100.0);
line.setStartY(150.0);
line.setEndX(500.0);
line.setEndY(150.0);
Rectangle & Rounded Rectangle Rectangle rectangle = new Rectangle();
Rectangle rectangle.setX(150.0f);
rectangle.setY(75.0f);
rectangle.setWidth(300.0f);
rectangle.setHeight(150.0f);
rectangle.setArcWidth(30.0);
rectangle.setArcHeight(20.0);
Circle Circle Circle circle = new Circle();
circle.setCenterX(300.0f);
circle.setCenterY(135.0f);
circle.setRadius(100.0f);

#3140705 (OOP-I)  Unit 07 – JavaFX basics 20


Classes for Shape (javafx.scene.shape) (Cont.)

Shape Class Example


Ellipse Ellipse Ellipse ellipse = new Ellipse();
ellipse.setCenterX(300.0f);
ellipse.setCenterY(150.0f);
ellipse.setRadiusX(150.0f);
ellipse.setRadiusY(75.0f);
Polygon Polygon Polygon polygon = new Polygon();
polygon.getPoints().addAll(new Double[]{
300.0, 50.0,
450.0, 150.0,
300.0, 250.0,
150.0, 150.0,
});

#3140705 (OOP-I)  Unit 07 – JavaFX basics 21


Classes for Shape (javafx.scene.shape) (Cont.)
Shape Class Example
Polyline Polyline Polyline polyline = new Polyline();
polyline.getPoints().addAll(new Double[]{
200.0, 50.0,
400.0, 50.0,
450.0, 150.0,
400.0, 250.0,
200.0, 250.0,
150.0, 150.0,
});
Cubic Curve CubicCurve CubicCurve cubicCurve = new CubicCurve();
cubicCurve.setStartX(100.0f);
cubicCurve.setStartY(150.0f);
cubicCurve.setControlX1(400.0f);
cubicCurve.setControlY1(40.0f);
cubicCurve.setControlX2(175.0f);
cubicCurve.setControlY2(250.0f);
cubicCurve.setEndX(500.0f);
cubicCurve.setEndY(150.0f);
#3140705 (OOP-I)  Unit 07 – JavaFX basics 22
Classes for Shape (javafx.scene.shape) (Cont.)

Shape Class Description


Quad Curve QuadCurve QuadCurve quadCurve = new QuadCurve();
quadCurve.setStartX(100.0);
quadCurve.setStartY(220.0f);
quadCurve.setEndX(500.0f);
quadCurve.setEndY(220.0f);
quadCurve.setControlX(250.0f);
quadCurve.setControlY(0.0f);
Arc Arc Arc arc = new Arc();
arc.setCenterX(100.0);
arc.setCenterY(100.0);
arc.setRadiusX(100.0);
arc.setRadiusY(100.0);
arc.setStartAngle(0.0);
arc.setLength(100.0);

#3140705 (OOP-I)  Unit 07 – JavaFX basics 23


Example (Adding 2-D Shapes)
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.shape.Ellipse;
import javafx.stage.Stage;

public class MyFirstGUI extends Application {


public void start(Stage primaryState) throws Exception { Create object of Ellipse
Ellipse ellipse = new Ellipse(); class and set its
ellipse.setCenterX(300.0f); ellipse.setCenterY(150.0f); properties.
ellipse.setRadiusX(150.0f); ellipse.setRadiusY(75.0f);
Pass object of ellipse as
Group root = new Group(ellipse); argument to Group
Scene s = new Scene(root, 600, 400); contructor
primaryState.setScene(s);
primaryState.show();
}
public static void main(String[] args) {
launch(args);
}
}
#3140705 (OOP-I)  Unit 07 – JavaFX basics 24
JavaFX - Colors
 javafx.scene.paint package provides various classes to apply colors to an application.
This package contains an abstract class named Paint and it is the base class of all the
classes that are used to apply colors.
 Using these classes, you can apply colors in the following patterns
 Uniform − color is applied uniformly throughout node.
 Image Pattern − fills the region of the node with an image pattern.
 Gradient − the color applied to the node varies from one point to the other. It has two kinds of gradients
namely Linear Gradient and Radial Gradient.
 Instance of Color class can be created by providing Red, Green, Blue and Opacity value
ranging from 0 to 1 in double.
Color color = new Color(double red, double green, double blue, double opacity);
Color color = new Color(0.0,0.3,0.2,1.0);
 Instance of Color class can be created using following methods also
Color c = Color.rgb(0,0,255); //passing RGB values
Color c = Color.hsb(270,1.0,1.0); //passing HSB values
Color c = Color.web("0x0000FF",1.0); //passing hex code
#3140705 (OOP-I)  Unit 07 – JavaFX basics 25
Applying Color to the Nodes
 setFill(Color) method is used to apply color to nodes such as Shape, Text, etc.
 setStroke(Color) method is used to apply strokes to the nodes.

//Setting color to the text


Color color = new Color.BEIGE
text.setFill(color);

//Setting color to the stroke


Color color = new Color.DARKSLATEBLUE
circle.setStroke(color);

#3140705 (OOP-I)  Unit 07 – JavaFX basics 26


Color Example
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
import javafx.scene.shape.Circle;

public class MyFirstGUI extends Application {


public void start(Stage stage) {
Circle circle = new Circle(); circle.setCenterX(300.0f); circle.setCenterY(180.0f);
circle.setRadius(90.0f);
circle.setFill(Color.RED); circle.setStrokeWidth(3); circle.setStroke(Color.GREEN);
Group root = new Group(circle);
Scene scene = new Scene(root, 600, 300);
stage.setScene(scene);
stage.show();
}
public static void main(String args[]) {
launch(args);
}
}
#3140705 (OOP-I)  Unit 07 – JavaFX basics 27
JavaFX – Image
 You can load and modify images using the classes provided by JavaFX in the package
javafx.scene.image.
 JavaFX supports the image formats like Bmp, Gif, Jpeg, Png.
 Class Image of javafx.scene.image package is used to load an image
 Any of the following argument is required to the constructor of the class
 An InputStream object of the image to be loaded or
FileInputStream inputstream = new FileInputStream ("C:\\image.jpg");
Image image = new Image(inputstream);
 A string variable holding the URL for the image.
Image image = new Image("http://sample.com/res/flower.png");
 After loading image in Image object, view is set to load the image using ImageView class
ImageView imageView = new ImageView(image);

#3140705 (OOP-I)  Unit 07 – JavaFX basics 28


Color Example (Image)
import java.io.FileInputStream; import javafx.application.Application;
import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.image.Image;
import javafx.scene.image.ImageView; import javafx.stage.Stage;

public class ImageExample extends Application {


public void start(Stage stage) throws Exception {
Image image = new Image(new FileInputStream("D://CEJDV.jpg"));
ImageView imageView = new ImageView(image);
imageView.setX(50);
imageView.setY(25);
imageView.setFitHeight(455);
imageView.setFitWidth(500);
imageView.setPreserveRatio(true);
Group root = new Group(imageView);
Scene scene = new Scene(root, 600, 500);
stage.setScene(scene);
stage.show();
}
public static void main(String args[]) { launch(args); }
}

#3140705 (OOP-I)  Unit 07 – JavaFX basics 29


Layout Panes
 After constructing all the required nodes in a scene, we will generally arrange them in order.
 This arrangement of the components within the container is called the Layout of the container.
 JavaFX provides several predefined layouts such as HBox, VBox, Border Pane, Stack Pane, Text
Flow, Anchor Pane, Title Pane, Grid Pane, Flow Panel, etc.
 Each of the above mentioned layout is represented by a class and all these classes belongs to
the package javafx.layout. The class named Pane is the base class of all the layouts in
JavaFX.

#3140705 (OOP-I)  Unit 07 – JavaFX basics 30


Layout Panes (javafx.scene.layout)
Sr. Shape & Description
1 HBox
• The HBox layout arranges all the nodes in our application in a single horizontal row.
• The class named HBox of the package javafx.scene.layout represents the text horizontal box layout.
2 VBox
• The VBox layout arranges all the nodes in our application in a single vertical column.
• The class named VBox of the package javafx.scene.layout represents the text Vertical box layout.
3 BorderPane
• The Border Pane layout arranges the nodes in our application in top, left, right, bottom and center
positions.
• The class named BorderPane of the package javafx.scene.layout represents the border pane layout.

#3140705 (OOP-I)  Unit 07 – JavaFX basics 31


Layout Panes (javafx.scene.layout) (Cont.)
Sr. Shape & Description
4 StackPane
• The stack pane layout arranges the nodes in our application on top of another just like in a stack.
The node added first is placed at the bottom of the stack and the next node is placed on top of it.
• The class named StackPane of the package javafx.scene.layout represents the stack pane layout.
5 TextFlow
• The Text Flow layout arranges multiple text nodes in a single flow.
• The class named TextFlow of the package javafx.scene.layout represents the text flow layout.
6 AnchorPane
• The Anchor pane layout anchors the nodes in our application at a particular distance from the pane.
• The class named AnchorPane of the package javafx.scene.layout represents the Anchor Pane
layout.

#3140705 (OOP-I)  Unit 07 – JavaFX basics 32


Layout Panes (javafx.scene.layout) (Cont.)
Sr. Shape & Description
7 TilePane
• The Tile Pane layout adds all the nodes of application in the form of uniformly sized tiles.
• The class named TilePane of the package javafx.scene.layout represents the TilePane layout.
8 GridPane
• The Grid Pane layout arranges the nodes in our application as a grid of rows and columns. This
layout comes handy while creating forms.
• The class named GridPane of the package javafx.scene.layout represents the GridPane layout.
9 FlowPane
• The flow pane layout wraps all the nodes in a flow. A horizontal flow pane wraps the elements of
the pane at its height, while a vertical flow pane wraps the elements at its width.
• The class named FlowPane of the package javafx.scene.layout represents the Flow Pane layout.

#3140705 (OOP-I)  Unit 07 – JavaFX basics 33


Creating a Layout
 To create a layout, you need to − public void start(Stage stage) {
 Create nodes. TextField textField = new TextField();
Button playButton = new Button("Play");
 Instantiate the respective class of Button stopButton = new Button("stop");
the required layout. HBox hbox = new HBox();
 Set the properties of the layout. hbox.setSpacing(10);
 Add all the created nodes to the hbox.setMargin(textField, new Insets(20, 20, 20, 20));
layout. hbox.setMargin(playButton, new Insets(20, 20, 20, 20));
hbox.setMargin(stopButton, new Insets(20, 20, 20, 20));
ObservableList<Node> list = hbox.getChildren();
list.addAll(textField, playButton, stopButton);
Scene scene = new Scene(hbox);
stage.setScene(scene);
stage.show();
}

#3140705 (OOP-I)  Unit 07 – JavaFX basics 34


JavaFX - Events
 In GUI applications, web applications and graphical applications, whenever a user interacts with
the application (nodes), an event is said to have been occurred.
 For example, clicking on a button, moving the mouse, entering a character through keyboard,
selecting an item from list, scrolling the page are the activities that causes an event to happen.
 JavaFX provides support to handle a wide varieties of events. The class named Event of the
package javafx.event is the base class for an event.
 JavaFX provides a wide variety of events. Some of them are as follows:
1. Mouse Event − occurs when a mouse is clicked.
o Class – MouseEvent
o Actions - mouse clicked, mouse pressed, mouse released, mouse moved, mouse entered target, mouse exited
target, etc.
2. Key Event − indicates the key stroke occurred on a node.
o Class – KeyEvent
o Actions - key pressed, key released and key typed.
3. Drag Event − occurs when the mouse is dragged.
o Class - DragEvent.
o Actions - drag entered, drag dropped, drag entered target, drag exited target, drag over, etc.
4. Window Event − occurs when window showing/hiding takes place.
o Class – WindowEvent
o Actions – window hiding, window shown, window hidden, window showing, etc.
#3140705 (OOP-I)  Unit 07 – JavaFX basics 35
Event Handling
 Event Handling is the mechanism that controls the event and decides what should happen, if an
event occurs. This mechanism has the code which is known as an event handler that is
executed when an event occurs.
 JavaFX provides handlers and filters to handle events. In JavaFX every event has
 Target − The node on which an event occurred. A target can be a window, scene, and a node.
 Source − The source from which the event is generated will be the source of the event.
 Type − Type of the occurred event; in case of mouse event – mouse pressed, mouse released are the type of
events.
 Phases of Event Handling
 Target selection
 Route Construction
 Event Capturing Phase
 Event Bubbling Phase

#3140705 (OOP-I)  Unit 07 – JavaFX basics 36


Event Handling Phases
 Target selection
 When an action occurs, the system determines which node is the target based on internal rules:
 Key events - the target is the node that has focus.
 Mouse events - the target is the node at the location of the cursor.
 Gesture events - the target is the node at the center point of all touches at the beginning of the gesture.
 Swipe events - the target is the node at the center of the entire path of all of the fingers.
 Touch events - the target for each touch point is the node at the location first pressed.
 Route Construction
 Whenever an event is generated, the default/initial route of the event is determined by construction of an
Event Dispatch chain. It is the path from the stage to the source node.
 Event Capturing Phase
 After the construction of the event dispatch chain, the root node of the application dispatches the event.
 This event travels to all nodes in the dispatch chain (from top to bottom).
 If any of these nodes has a filter registered for the generated event, it will be executed.
 If none of the nodes in the dispatch chain has a filter for the event generated, then it is passed to the target
node and finally the target node processes the event.
#3140705 (OOP-I)  Unit 07 – JavaFX basics 37
Event Handling Phases (Cont.)
 Event Bubbling Phase
 In the event bubbling phase, the event is travelled from the target node to the stage node (bottom to top).
 If any of the nodes in the event dispatch chain has a handler registered for the generated event, it will be
executed.
 If none of these nodes have handlers to handle the event, then the event reaches the root node and finally the
process will be completed.

#3140705 (OOP-I)  Unit 07 – JavaFX basics 38


Event Handlers and Filters
 Event filters and handlers are those which contains application logic to process an event.
 A node can register to more than one handler/filter. In case of parent–child nodes, you can
provide a common filter/handler to the parents, which is processed as default for all the child
nodes.
 During the event capturing phase, a filter is executed and during the event bubbling phase, a
handler is executed.
 All the handlers and filters implement the interface EventHandler of the package
javafx.event.

#3140705 (OOP-I)  Unit 07 – JavaFX basics 39


Handling Mouse Event
public class JavafxSample extends Application { EventHandler<MouseEvent> mouseHandler =
public static void main(String[] args) { new EventHandler<MouseEvent>(){
launch(args); @Override
} public void handle(MouseEvent mouseEvent){
public void start(Stage primaryStage) { System.out.println(
Group root = new Group(); mouseEvent.getEventType() + "\n" +
Scene scene = "X : Y - "
new Scene(root, 300, 250); + mouseEvent.getX() + " : " +
scene.setOnMouseClicked(mouseHandler); mouseEvent.getY() + "\n" +
scene.setOnMouseDragged(mouseHandler); "SceneX : SceneY - "
scene.setOnMouseEntered(mouseHandler); + mouseEvent.getSceneX()+" :
scene.setOnMouseExited(mouseHandler); "+mouseEvent.getSceneY() +
scene.setOnMouseMoved(mouseHandler); "\n" + "ScreenX : ScreenY - "
scene.setOnMousePressed(mouseHandler); + mouseEvent.getScreenX()+" :
scene.setOnMouseReleased(mouseHandler); "+mouseEvent.getScreenY());
}
primaryStage.setScene(scene); };
primaryStage.show(); }
}

#3140705 (OOP-I)  Unit 07 – JavaFX basics 40


Creating a Calculator using JavaFX

#3140705 (OOP-I)  Unit 07 – JavaFX basics 41


Animation
 JavaFX provides easy to use animation API (javafx.animation package).
 There are some predefined animation that can be used out of the box or you can implement
custom animations using KeyFrames.
 Following are the main predefined animations in JavaFX.
 TranslateTransition: Translate transition allows to create movement animation from one point to another
within a duration. Using TranslateTransition#setByX / TranslateTransition#setByY, you can set how much it
should move in x and y axis respectively. It also possible to set precise destination by using
TranslateTransition#setToX / TranslateTransition#setToY.
 ScaleTransition: Scale transition is another JavaFX animation which can be used out of the box that allows
to animate the scale / zoom of the given object. The object can be enlarged or minimized using this
animation.
 RotateTransition: Rotate transition provides animation for rotating an object. We can provide upto what
angle the node should rotate by toAngle. Using byAngle we can specify how much it should rotate from
current angle of rotation.
 FadeTransition: Fade transition creates a fade in / fade out effect by controlling opacity of the object. We
can make fade in transition or fade out transition in JavaFX by setting the to and from value.
 PathTransition: Path transition provides option to move object through a specified path. The path can be
anything from simple straight line to complex quadratic curves.
#3140705 (OOP-I)  Unit 07 – JavaFX basics 42
Example Animation
@Override
public void start(Stage primaryStage) throws Exception {
// TODO Auto-generated method stub
Rectangle rect = new Rectangle(200,400);
rect.setX(400);
rect.setY(150);

Group root = new Group(rect);

Scene s = new Scene(root, 1000,700);

Duration dt = new Duration(2500);


RotateTransition rt = new RotateTransition(dt,rect);
rt.setByAngle(180);
rt.play();

primaryStage.setScene(s);
primaryStage.show();

#3140705 (OOP-I)  Unit 07 – JavaFX basics 43


Exercise
 Creating a Calculator using JavaFX
 Write a program that displays a tic-tac-toe board. A cell may be X, O, or empty. What to display
at each cell is randomly decided. The X and O are images in the files X.gif and O.gif.
 Write a program that displays the color of a circle as red when the mouse button is pressed and
as white when the mouse button is released.

#3140705 (OOP-I)  Unit 07 – JavaFX basics 44

You might also like