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

10-JavaFX

The document provides a comprehensive tutorial on JavaFX, covering its installation, features, and core concepts such as GUI components, stages, scenes, and nodes. It includes links to video lectures and resources for further learning, as well as code examples for creating JavaFX applications. Key topics include event handling, Scene Builder, and the lifecycle of JavaFX applications.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

10-JavaFX

The document provides a comprehensive tutorial on JavaFX, covering its installation, features, and core concepts such as GUI components, stages, scenes, and nodes. It includes links to video lectures and resources for further learning, as well as code examples for creating JavaFX applications. Key topics include event handling, Scene Builder, and the lifecycle of JavaFX applications.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 25

Elearning Lectures

v JavaFx Tutorial For Beginners


https://www.youtube.com/watch?v=9YrmON6nlEw&
list=PLS1QulWo1RIaUGP446_pWLgTZPiFizEMq
GUI Programming with v Khóa học lập trình JavaFX

JavaFX https://www.youtube.com/watch?v=zAq7Lmv46PE&l
ist=PL33lvabfss1yRgFCgFXjtYaGAuDJjjH-j

1 2

1 2

Content Content
1. Introduction 1. Introduction
2. JavaFX Installment 2. JavaFX Installment
3. GUI components in JavaFX 3. GUI components in JavaFX
4. JavaFX - UI controls 4. JavaFX - UI controls
5. JavaFX - Layout Panes 5. JavaFX - Layout Panes
6. Event handling models 6. Event handling models
7. “Drag and drop” GUI with SceneBuilder 7. “Drag and drop” GUI with SceneBuilder

3 4

3 4

1
1. Introduction 1. Introduction
v A graphical user interface - GUI (pronounced Title bar
Menus
"GOO-ee"): Combo box
Menu bar
§ is a type of user interface
§ allows users to interact with electronic devices using images
rather than text commands
v Why use term GUI? Button
§ The first interactive user interfaces to computers were not Scroll bar
graphical

5 6

5 6

Java APIs for GUI programming JavaFX – Features


v Two core sets of Java APIs for graphics programming: v Written in Java − The JavaFX library is written in Java and is
§ AWT (Abstract Windowing Toolkit) available for the languages that can be executed on a JVM.
§ Swing v FXML − JavaFX features a language known as FXML, which
v AWT: is a HTML like declarative markup language. The sole
§ introduced in JDK 1.0
purpose of this language is to define a user Interface.
§ should be replaced by newer Swing components v Scene Builder − JavaFX provides an application named
v Swing: Scene Builder. The users can access a drag and drop design
interface, which is used to develop FXML applications
§ enhances AWT
§ integrated into core Java since JDK 1.2 v Swing Interoperability − In a JavaFX application, you can
embed Swing content using the Swing Node class
v Others:
§ Eclipse's Standard Widget Toolkit (SWT) v Built-in UI controls − JavaFX library caters UI controls using
§ Google Web Toolkit (GWT) which we can develop a full-featured application.
§ 3D Graphics API such as Java bindings for OpenGL (JOGL) and v CSS like Styling − JavaFX provides a CSS like styling. By
Java3D. using this, you can improve the design of your application
with a simple knowledge of CSS.

7 8

7 8

2
History of JavaFX Content
v JavaFX was originally developed by Chris Oliver, when 1. Introduction
he was working for a company named See Beyond
Technology Corporation, which was later acquired 2. JavaFX Installment
by Sun Microsystems in the year 2005. 3. GUI components in JavaFX
v In the year 2007, JavaFX was announced officially
at Java One, a world wide web conference which is 4. JavaFX - UI controls
held yearly. 5. JavaFX - Layout Panes
v In the year 2008, Net Beans integrated with JavaFX 6. Event handling models
was available. In the same year, the Java Standard
Development Kit for JavaFX 1.0 was released. 7. “Drag and drop” GUI with SceneBuilder
v The latest version, JavaFX8, was released as an
integral part of Java on 18th of March 2014.
v 2018: JavaFX is taken out of Java SDK 11

9 10

9 10

2. JavaFX Installment
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
JavaFX Hello World
import javafx.scene.Scene;
v JavaFX home page: https://openjfx.io/ import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
v JavaFX downloading page: import javafx.stage.Stage;

https://gluonhq.com/products/javafx/ public class HelloWorld extends Application {


@Override
public void start(Stage primaryStage) {
v Download, decompress, copy files from the lib Button btn = new Button();
btn.setText("Say 'Hello World'");
folder and add to project build path btn.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
v Note to run JavaFX in Eclipse System.out.println("Hello World!");
}
§ Go to runtime configuration and configure VM arguments as follows: });
• --module-path StackPane root = new StackPane();
${project_classpath:REPLACE_ME_WITH_YOUR_PROJECT_NAME} --add- root.getChildren().add(btn);
modules javafx.controls,javafx.fxml
§ Uncheck: “Use the -XstartOnFirstThread argument when Scene scene = new Scene(root, 300, 250);
launching with SWT” primaryStage.setTitle("Hello World!");
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
11 } 12
}

11 12

3
JavaFX plug-ins in Eclipse e(fx)clipse installment
v e(fx)clipse
§ https://www.eclipse.org/efxclipse/releases.html
§ Is an Eclipse plugin
§ Support JavaFX programming in Eclipse
v JavaFX Scene Builder
§ https://www.oracle.com/java/technologies/javafxscenebuilder-1x-
archive-downloads.html
§ Is an independent tool, platform-independent, support
visual programming
§ Users can drag and drop GUI components, change their
properties, apply visual styles
§ Output: FXML file used in JavaFX programs

13 14

13 14

e(fx)clipse installment e(fx)clipse installment

Nhập vào:
http://download.eclipse.org/efxclipse/updates-
released/3.0.0/site

Xem các Phiên bản mới nhất tại:


https://www.eclipse.org/efxclipse/releases.html

15 16

15 16

4
e(fx)clipse installment e(fx)clipse installment

17 18

17 18

e(fx)clipse installment Add JavaFX Scene Builder to Eclipse


v After the instamment, we restart Eclipse, go to menu v Download and install JavaFX Scene Builder
File/New/Others ... we will see JavaFX Wizards
v Open Eclipse, go to Window/Preferences

19 20

19 20

5
Add JavaFX Scene Builder to Eclipse Add JavaFX Scene Builder to Eclipse

21 22

Add JavaFX Scene Builder to Eclipse Content


1. Introduction
2. JavaFX Installment
3. GUI components in JavaFX
4. JavaFX - UI controls
5. JavaFX - Layout Panes
6. Event handling models
7. “Drag and drop” GUI with SceneBuilder

24

23 24

6
3. GUI components in JavaFX Stage
v 3 main concepts of JavaFX applications: Stage, v A stage (a window) contains all the objects of a JavaFX
application.
Scene, and Nodes
v It is represented by Stage class of the
package javafx.stage
v Stage object is passed as an argument to
the start() method of the Application class (See the
HelloWorld JavaFX example)
v A stage has two parameters determining its position
namely Width and Height.
v It is divided as Content Area and Decorations (Title Bar
and Borders).
v You have to call the show() method to display the
contents of a stage.
v There are five types of stages available: Decorated,
Undecorated, Transparent, Unified, Utility

25 26

25 26

Stage – set the style


import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
JavaFX Hello World
import javafx.scene.Scene;
stage.initStyle(StageStyle.DECORATED); import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
//stage.initStyle(StageStyle.UNDECORATED); import javafx.stage.Stage;
//stage.initStyle(StageStyle.TRANSPARENT); public class HelloWorld extends Application {
@Override
//stage.initStyle(StageStyle.UNIFIED); public void start(Stage primaryStage) {
//stage.initStyle(StageStyle.UTILITY); Button btn = new Button();
btn.setText("Say 'Hello World'");
btn.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
System.out.println("Hello World!");
}
});
StackPane root = new StackPane();
root.getChildren().add(btn);
Scene scene = new Scene(root, 300, 250);
primaryStage.setTitle("Hello World!");
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
27 } 28
}

27 28

7
Scene Scene Graph and Nodes
v A scene represents the physical contents of a JavaFX v Scene graph: is a tree-like data structure (hierarchical)
application. It contains all the contents of a scene representing the contents of a scene.
graph.
v In contrast, a node is a visual/graphical object of a
v The class Scene of the
scene graph. A node may include −
package javafx.scene represents the scene object.
§ Geometrical (Graphical) objects (2D and 3D) such as − Circle,
v At an instance, the scene object is added to only one Rectangle, Polygon, etc.
stage. § UI Controls such as − Button, Checkbox, Choice Box, Text Area, etc.
v You can create a scene by instantiating the Scene § Containers (Layout Panes) such as Border Pane, Grid Pane, Flow
Pane, etc.
Class. You can opt for the size of the scene by passing
its dimensions (height and width) along with the root § Media elements such as Audio, Video and Image Objects
node to its constructor. v The Node Class of the package javafx.scene
§ Scene(Parent root) represents a node in JavaFX, this class is the super
§ Scene(Parent root, double width, double height)
class of all the nodes
§ …

29 30

29 30

Scene Graph and Nodes JavaFX node class hierarchy


A node is of three types javafx.scene.Node
v Root Node − The first Scene Graph is known as the Root
node.
v Branch Node/Parent Node − The node with child nodes
are known as branch/parent nodes. The abstract class javafx.scene.Parent
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. Whenever the group node is rendered, all its child
nodes are rendered in order. Any transformation, effect state applied
on the group will be applied to all the child nodes.
§ Region − It is the base class of all the JavaFX Node based UI Controls,
such as Chart, Pane and Control.
javafx.scene.Group javafx.scene.layout.Region
§ WebView − This node manages the web engine and displays its
contents.
v Leaf Node − The node without child nodes is known as the
leaf node. Rectangle, Ellipse, Box, ImageView, MediaView
are examples of leaf nodes.
javafx.scene.chart.Chart javafx.scene.layout.Pane javafx.scene.control.Control
31 32

31 32

8
Creating a JavaFX Application Lifecycle of JavaFX Application
v To create a JavaFX application, you need to instantiate the Application v JavaFX Application class has three life cycle methods:
class and implement its abstract method start(). start(), stop(), init()
v In the main method, you have to launch the application using v They do nothing by default. You can override to
the launch() method. This method internally calls the start() method implement something
of the Application class v Whenever a JavaFX application is launched, the
public class JavafxSample extends Application { following actions will be carried out
@Override § An instance of the application class is created.
public void start(Stage primaryStage) throws Exception { § Init() method is called.
/* § The start() method is called.
Code for JavaFX application. § The launcher waits for the application to finish and calls
the stop() method
(Stage, scene, scene graph)
*/
v When the last window of the application is closed, the
}
JavaFX application is terminated implicitly
public static void main(String args[]){ v You can terminate a JavaFX application explicitly using
launch(args); the methods Platform.exit() or System.exit(int)
}
}

33 34

33 34

The start method Preparing the Scene Graph


v In order to create a typical JavaFX application, you v You need to create a root node first, it can be
need to follow three steps in the start method: Group, Region or WebView
§ Prepare a scene graph with the required nodes. § VD: Group root = new Group();
§ Prepare a Scene with the required dimensions and add the v We can add node to root node in 2 ways
scene graph (root node of the scene graph) to it.
§ Way 1:
§ Prepare a stage and add the scene to the stage and display //Retrieving the observable list object
the contents of the stage ObservableList list = root.getChildren();

//Setting a node object as a node


list.add(NodeObject);
§ Way 2:

Group root = new Group(NodeObject);

35 36

35 36

9
Preparing the Scene Preparing the Stage
v While instantiating Scene, it is mandatory to pass v An object of Stage class is passed as a parameter
the root object to the constructor of the scene of the start() method of the Application class à
class. We do not need to instantiate it
Scene scene = new Scene(root); v Using this object, you can perform various
operations on the stage. Primarily you can
perform the following
v You can also pass two parameters of double type
representing the height and width of the scene as //Setting the title to Stage.
shown below. primaryStage.setTitle("Sample application");

//Setting the scene to Stage


Scene scene = new Scene(root, 600, 300); primaryStage.setScene(scene);

//Displaying the stage


primaryStage.show();

37 38

37 38

Example: Creating an Empty Window Example: Creating an Empty Window

public class JavafxSample extends Application {


@Override
public void start(Stage primaryStage) throws Exception {
//creating a Group object
Group group = new Group();
//Creating a Scene
Scene scene = new Scene(group ,600, 300);
//setting color to the scene
scene.setFill(Color.BROWN);
//Setting the title to Stage.
primaryStage.setTitle("Sample Application");
//Adding the scene to Stage
primaryStage.setScene(scene);

//Displaying the contents of the stage


primaryStage.show();
}
public static void main(String args[]){
launch(args);
} 39 40
}

39 40

10
Example: Drawing a Straight Line Example: Drawing a Straight Line
public class DrawingLine extends Application{
@Override
public void start(Stage stage) {
//Creating a line object
Line line = new Line();

//Setting the properties to a line


line.setStartX(100.0);
line.setStartY(150.0);
line.setEndX(500.0);
line.setEndY(150.0);

//Creating a Group
Group root = new Group(line);

//Creating a Scene
Scene scene = new Scene(root, 600, 300);
//Setting title to the scene
stage.setTitle("Sample application");

//Adding the scene to the stage


stage.setScene(scene);
//Displaying the contents of a scene
stage.show();
}
public static void main(String args[]){
launch(args);
}
}

41 42

41 42

public class DisplayingText extends Application {


@Override Example: Displaying Text
public void start(Stage stage) {
//Creating a Text object
Text text = new Text();
Example: Displaying Text

//Setting font to the text


text.setFont(new Font(45));

//setting the position of the text


text.setX(50);
text.setY(150);
//Setting the text to be added.
text.setText("Welcome to Tutorialspoint");

//Creating a Group object


Group root = new Group();
//Retrieving the observable list object
ObservableList list = root.getChildren();
//Setting the text object as a node to the group object
list.add(text);
//Creating a scene object
Scene scene = new Scene(root, 600, 300);
//Setting title to the Stage
stage.setTitle("Sample Application");
//Adding scene to the stage
stage.setScene(scene);
//Displaying the contents of the stage
stage.show();
}
public static void main(String args[]){
launch(args);
}
} 43 44

43 44

11
Example: Text decoration Example: Text decoration
public class DecorationsExample extends Application { //setting the position of the text
@Override text2.setX(50);
public void start(Stage stage) { text2.setY(150);
//Creating a Text_Example object
Text text1 = new Text("Hi how are you"); //underlining the text
//Setting font to the text text2.setUnderline(true);
text1.setFont(
Font.font("verdana", FontWeight.BOLD, FontPosture.REGULAR, 20) //Creating a Group object
); Group root = new Group(text1, text2);
//setting the position of the text //Creating a scene object
text1.setX(50); Scene scene = new Scene(root, 600, 300);
text1.setY(75);
//Striking through the text //Setting title to the Stage
text1.setStrikethrough(true); stage.setTitle("Decorations Example");
//Creating a Text_Example object //Adding scene to the stage
Text text2 = new Text("Welcome to Tutorialspoint"); stage.setScene(scene);
//Setting font to the text //Displaying the contents of the stage
text2.setFont( stage.show();
Font.font("verdana", FontWeight.BOLD, FontPosture.REGULAR, 20)
); }
public static void main(String args[]){
launch(args);
}
}

45 46

45 46

Example: Text decoration Content


1. Introduction
2. JavaFX Installment
3. GUI components in JavaFX
4. JavaFX - UI controls
5. JavaFX - Layout Panes
6. Event handling models
7. “Drag and drop” GUI with SceneBuilder

47 48

47 48

12
4. Java FX - UI Controls 4. Java FX - UI Controls
Every user interface considers the following three
main aspects:
v UI elements − These are the core visual elements
which the user eventually sees and interacts with.
JavaFX provides a huge list of widely used and
common elements varying from basic to complex
v Layouts − They define how UI elements should be
organized on the screen and provide a final look
and feel to the GUI (Graphical User Interface).
v Behavior − These are events which occur when
the user interacts with UI elements.

49 50

49 50

4. Java FX - UI Controls Login Page Example (1/5)


v Develop a JavaFX application as shown belows:

51 52

51 52

13
Login Page Example (2/5) Login Page Example (3/5)
public class LoginPage extends Application {
import javafx.application.Application;
@Override
import static javafx.application.Application.launch;
public void start(Stage stage) {
import javafx.geometry.Insets;
//creating label email
import javafx.geometry.Pos;
Text text1 = new Text("Email");
import javafx.scene.Scene;
//creating label password
import javafx.scene.control.Button;
Text text2 = new Text("Password");
import javafx.scene.control.PasswordField;
import javafx.scene.layout.GridPane;
//Creating Text Filed for email
import javafx.scene.text.Text;
TextField textField1 = new TextField();
import javafx.scene.control.TextField;
import javafx.stage.Stage;
//Creating Text Filed for password
PasswordField textField2 = new PasswordField();

//Creating Buttons
Button button1 = new Button("Submit");
Button button2 = new Button("Clear");

53 54

53 54

Login Page Example (4/5) Login Page Example (5/5)


//Creating a Grid Pane
GridPane gridPane = new GridPane(); //Styling nodes
button1.setStyle("-fx-background-color: darkslateblue; -fx-text-fill: white;");
button2.setStyle("-fx-background-color: darkslateblue; -fx-text-fill: white;");
//Setting size for the pane
gridPane.setMinSize(400, 200); text1.setStyle("-fx-font: normal bold 20px 'serif' ");
text2.setStyle("-fx-font: normal bold 20px 'serif' ");
//Setting the padding gridPane.setStyle("-fx-background-color: BEIGE;");
gridPane.setPadding(new Insets(10, 10, 10, 10));
//Creating a scene object
Scene scene = new Scene(gridPane);
//Setting the vertical and horizontal gaps between the columns
gridPane.setVgap(5); //Setting title to the Stage
gridPane.setHgap(5); stage.setTitle("CSS Example");

//Setting the Grid alignment //Adding scene to the stage


gridPane.setAlignment(Pos.CENTER); stage.setScene(scene);

//Displaying the contents of the stage


//Arranging all the nodes in the grid
stage.show();
gridPane.add(text1, 0, 0); }
gridPane.add(textField1, 1, 0); public static void main(String args[]){
gridPane.add(text2, 0, 1); launch(args);
gridPane.add(textField2, 1, 1); }
gridPane.add(button1, 0, 2); }
gridPane.add(button2, 1, 2);
55 56

55 56

14
Content 5. JavaFX - Layout Panes (Container)
1. Introduction v After constructing all the required nodes in a
scene, we will generally arrange them in order.
2. JavaFX Installment
v This arrangement of the components within the
3. GUI components in JavaFX container is called the Layout of the container.
4. JavaFX - UI controls v JavaFX provides several predefined layouts such
5. JavaFX - Layout Panes as HBox, VBox, Border Pane, Stack Pane, Text
Flow, Anchor Pane, Title Pane, Grid Pane, Flow
6. Event handling models Panel, etc.
7. “Drag and drop” GUI with SceneBuilder v 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.

57 58

57 58

Creating a Layout HBox layout


v To create a layout, you need to v HBox layout: all the nodes are set in a single horizontal
§ Create node. row.
§ Instantiate the respective class of the required layout. v Important properties:
§ Set the properties of the layout. § alignment − represents the alignment of the nodes in the bounds
§ Add all the created nodes to the layout. of the HBox.
§ spacing − is of double type and represents the space between the
children of the HBox.
v Khởi tạo HBox
// Khởi tạo rỗng
HBox hbox = new HBox();

// Khởi tạo với các node


Button button1 = new Button("Button Number 1");
Button button2 = new Button("Button Number 2");
HBox hbox = new HBox(button1, button2);

59 60

59 60

15
HBox layout example HBox layout example
import javafx.application.Application; import javafx.application.Application;
import javafx.geometry.Pos; import javafx.geometry.Pos;
import javafx.scene.Scene; import javafx.scene.Scene;
import javafx.scene.control.Button; import javafx.scene.control.Button;
import javafx.scene.layout.HBox; import javafx.scene.layout.HBox;
import javafx.stage.Stage; import javafx.stage.Stage;
public class HBoxExperiments extends Application { public class HBoxExperiments extends Application {
@Override @Override
public void start(Stage primaryStage) throws Exception { public void start(Stage primaryStage) throws Exception {
primaryStage.setTitle("HBox Experiment 1"); primaryStage.setTitle("HBox Experiment 1");
Button button1 = new Button("Button Number 1"); Button button1 = new Button("Button Number 1");
Button button2 = new Button("Button Number 2"); Button button2 = new Button("Button Number 2");
Button button3 = new Button("Button Number 3"); Button button3 = new Button("Button Number 3");
HBox hbox = new HBox(button1, button2); HBox hbox = new HBox(button1, button2);
hbox.setSpacing(10); hbox.setSpacing(10);
hbox.setAlignment(Pos.BOTTOM_CENTER); hbox.setAlignment(Pos.BOTTOM_CENTER);
hbox.getChildren().add(button3); hbox.getChildren().add(button3);
Scene scene = new Scene(hbox, 400, 100); Scene scene = new Scene(hbox, 400, 100);
primaryStage.setScene(scene); primaryStage.setScene(scene);
primaryStage.show(); primaryStage.show();
} }
} }
61 62

61 62

HBox layout example Group layout


v Group layout do not arrange its components. All are in (0, 0)

import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.stage.Stage;
BOTTOM_CENTER public class GroupExperiments extends Application {
@Override
public void start(Stage primaryStage) throws Exception {
primaryStage.setTitle("HBox Experiment 1");
Button button1 = new Button("Button Number 1");
Button button2 = new Button("Button 2");
BASELINE_RIGHT
Group group = new Group();
group.getChildren().add(button1);
group.getChildren().add(button2);
Scene scene = new Scene(group, 200, 100);
primaryStage.setScene(scene);
primaryStage.show(); 2 button đều ở tọa độ (0,
TOP_LEFT } 0), đè lên nhau
}
63 64

63 64

16
Other layouts Other layouts
v FlowPane: wraps all the nodes in a flow. A v GridPane layout: arranges the nodes in our application as a
horizontal flow pane wraps the elements of the grid of rows and columns. This layout comes handy while
pane at its height, while a vertical flow pane wraps creating forms using JavaFX.
the elements at its width v

65 66

65 66

Other layouts Other layouts


v BorderPane layout: arranges the nodes in our application v BorderPane: if an area is empty, the other will take its
in top, left, right, bottom and center positions. space
v Example: empty TOP area

67 68

67 68

17
Content 6. Event Handling
1. Introduction v The events can be broadly classified into the
2. JavaFX Installment following two categories
§ Foreground Events require the direct interaction of a user.
3. GUI components in JavaFX They are generated as consequences of a person interacting
with the graphical components in a Graphical User Interface.
4. JavaFX - UI controls For example, clicking on a button, moving the mouse,
5. JavaFX - Layout Panes entering a character through keyboard, selecting an item
from list, scrolling the page, etc.
6. Event handling models § Background Events don't require the interaction of end-
7. “Drag and drop” GUI with SceneBuilder user. The operating system interruptions, hardware or
software failure, timer expiry, operation completion are the
example of background events

69 70

69 70

6. Event Handling 6. Event Handling


v Class javafx.event.Event is the base class for an event. v Event Handling is the mechanism that controls the
v An instance of any of its subclass is an event. JavaFX event and decides what should happen, if an
provides a wide variety of events: event occurs. This mechanism has the code which
§ Mouse Event occurs when a mouse is clicked. It is represented by the is known as an event handler that is executed
class named MouseEvent. It includes actions like mouse clicked, mouse when an event occurs.
pressed, mouse released, mouse moved, mouse entered target, mouse
exited target, etc. v JavaFX provides handlers and filters to handle
§ Key Event indicates the key stroke occurred on a node. It is represented events. In JavaFX every event has −
by the class named KeyEvent. This event includes actions like key pressed, § Target − The node on which an event occurred. A target can
key released and key typed.
be a window, scene, and a node.
§ Drag Event occurs when the mouse is dragged. It is represented by the
class named DragEvent. It includes actions like drag entered, drag § Source − The source from which the event is generated will
dropped, drag entered target, drag exited target, drag over, etc. be the source of the event. In the above scenario, mouse is
§ Window Event is related to window showing/hiding actions. It is the source of the event.
represented by the class named WindowEvent. It includes actions like § Type − Type of the occurred event; in case of mouse event –
window hiding, window shown, window hidden, window showing, etc. mouse pressed, mouse released are the type of events.

71 72

71 72

18
Example Event Delivery Process
v If we click on the play button, the source will be v The event delivery process contains the following
the mouse, the target node will be the play button steps:
and the type of the event generated is the mouse § Target selection
click. § Route construction
§ Event capturing
§ Event bubbling
https://docs.oracle.com/javafx/2/events/processing.htm

73 74

73 74

Event Delivery Process Event Delivery Process


v Step 1: Target selection (identify target node). v Step 2: Route Construction – create the Event
When an action occurs, the system determines Dispatch chain: the route from stage to target
which node is the target based on internal rules: node
§ For key events, the target is the node that has focus.
§ For mouse events, the target is the node at the location of
the cursor. For synthesized mouse events, the touch point is
considered the location of the cursor.
§ For swipe events that are generated by a swipe on a touch
screen, the target is the node at the center of the entire
path of all of the fingers. For indirect swipe events, the
target is the node at the location of the cursor.
§ For touch events, the default target for each touch point is
the node at the location first pressed. A different target can
be specified using the ungrab(), grab(),
or grab(node) methods for a touch point in an event filter or
event handler.

75 76

75 76

19
Event Delivery Process Event Delivery Process
v Step 3: Event Capturing v Step 4: Event Bubbling
§ In the event capturing phase, the event is dispatched by the § After the event target is reached and all registered filters
root node of your application and passed down the event have processed the event, the event returns along the
dispatch chain to the target node. dispatch chain from the target to the root node.
§ If any node in the chain has an event filter registered for the § If any node in the chain has a handler registered for the type
type of event that occurred, that filter is called. of event encountered, that handler is called.
§ When the filter completes, the event is passed to the next § When the handler completes, the event is returned to the
node down the chain. next node up the chain.
§ If a filter is not registered for a node, the event is passed to § If a handler is not registered for a node, the event is
the next node down the chain. returned to the next node up the chain.
§ If no filter consumes the event, the event target eventually § If no handler consumes the event, the root node eventually
receives and processes the event. receives the event and processing is completed.

77 78

77 78

Event Delivery Process Add/remove filter


v Event filters and handlers are those which v Add filter
contains application logic to process an event.
//Creating the mouse event handler
v A node can register to more than one EventHandler<MouseEvent> eventFilter = new EventHandler<MouseEvent>() {
@Override
handler/filter. public void handle(MouseEvent e) {
System.out.println("Hello World");
v In case of parent–child nodes, you can provide a }
circle.setFill(Color.DARKSLATEBLUE);
common filter/handler to the parents, which is };
processed as default for all the child nodes. //Adding event Filter
circle.addEventFilter(MouseEvent.MOUSE_CLICKED, eventFilter);
v All the handlers and filters implement the
interface EventHandler of the package
javafx.event.
v Remove filter
circle.removeEventFilter(MouseEvent.MOUSE_CLICKED, eventFilter);

79 80

79 80

20
Add/Remove handler import javafx.application.Application;
import javafx.event.EventHandler; Example (1/3)
import javafx.scene.Scene;
v Add handler import javafx.scene.control.Button;
import javafx.scene.control.TextArea;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.FlowPane;
//Creating the mouse event handler import javafx.scene.shape.Circle;
EventHandler<MouseEvent> eventHandler = new EventHandler<MouseEvent>() { import javafx.stage.Stage;
@Override
public void handle(MouseEvent e) {
public class EventFiltersExample extends Application {
System.out.println("Hello World"); @Override
circle.setFill(Color.DARKSLATEBLUE); public void start(Stage stage) {
} Button button = new Button("Button");
}; TextArea text = new TextArea();
Circle circle = new Circle(25.0f);
//Adding event handler
circle.addEventHandler(MouseEvent.MOUSE_CLICKED, eventHandler); FlowPane fp = new FlowPane(button, text, circle);
fp.addEventFilter(MouseEvent.MOUSE_CLICKED, new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent arg0) {
text.appendText("Filter in flow pane\n");
}
v Remove handler });
fp.addEventHandler(MouseEvent.MOUSE_CLICKED, new EventHandler<MouseEvent>() {
@Override
circle.removeEventHandler(MouseEvent.MOUSE_CLICKED, eventHandler); public void handle(MouseEvent arg0) {
text.appendText("Handler in flow pane\n");
}
});
81 82

81 82

button.addEventFilter(MouseEvent.MOUSE_CLICKED, new EventHandler<MouseEvent>() {


@Override
public void handle(MouseEvent arg0) { Example (2/3) Example (3/3)
text.appendText("Filter in button\n");
}
});
button.addEventHandler(MouseEvent.MOUSE_CLICKED, new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent arg0) {
text.appendText("Handler in button\n");
}
});
import javafx.application.Application;
circle.addEventFilter(MouseEvent.MOUSE_CLICKED, new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent arg0) { public final class Main {
text.appendText("Filter in circle\n"); public static void main(final String[] args) {
} Application.launch(EventFiltersExample.class, args);
});
circle.addEventHandler(MouseEvent.MOUSE_CLICKED, new EventHandler<MouseEvent>() { }
@Override }
public void handle(MouseEvent arg0) {
text.appendText("Handler in circle\n");
}
});
// Creating a scene object
Scene scene = new Scene(fp, 600, 300);
stage.setTitle("Event Filters Example");
stage.setScene(scene);
stage.show();
}
}
83 84

83 84

21
Example Example
v When click on the circle v When click on Button

Note the order


1. Filter is called first, then Handler Note: Hanlder of flow pane do not called like we click
2. Filter of flow pane is called before Filter of circle on circle. It is because the handler of button consumes
3. Handler of circle is called before Handler of flow pane event by default

85 86

85 86

Example Example
v Update the source code of flow pane as follows v When click on circle (or button), because the
event is consumed, the result will be as follows

fp.addEventFilter(MouseEvent.MOUSE_CLICKED, new EventHandler<MouseEvent>() {


@Override
public void handle(MouseEvent arg0) {
text.appendText("Filter in flow pane\n");
arg0.consume();
}
});

87 88

87 88

22
Content 7. “Drag and drop” GUI with SceneBuilder
1. Introduction v Idea: seperate the interface with the business logic
§ Interface: defined in file fxml
2. JavaFX Installment § Business Logic (controller): is separated in Java source code
3. GUI components in JavaFX v To work with SceneBuilder:
4. JavaFX - UI controls § Install SceneBuilder
§ Create interface (and then generate fxml file), define the
5. JavaFX - Layout Panes component properties (name of component, event handling
methods)
6. Event handling models § Create a JavaFX project
7. “Drag and drop” GUI with SceneBuilder § Copy fxml file to JavaFX project
§ Create controller
§ Connect the fxml file with the controller
§ Create JavaFX application, load fxml file

89 90

89 90

Example Create SayHello.fxml file with SceneBuilder


v Develop an application with the following interface. When
we click on the button “Say Hello”, the text Hello World is
printed in the textbox
Drag and drop VBox container

Similarly, drage and drop a


Button and a Textarea (expand
the “Controls” tab)

91 92

91 92

23
Specify button properties Specify button properties

Vẫn chọn Button, vào tab Code bên


Chọn Button, vào tab Properties phải, sửa thuộc tính id là
bên phải, sửa thuộc tính Text là sayHelloButton, sửa thuộc tính
“Say Hello” onAction là sayHello. Tương tự, sửa
id của TextArea là textHello

93 94

93 94

Create project JavaFX Create controller class: MyController


import java.net.URL;
import java.util.ResourceBundle;
v Create a Java project as normal, import javafx.event.ActionEvent; Note: names of Button and
TextArea must correspond
then copy file SayHello.fxml to the import javafx.fxml.FXML;
import javafx.fxml.Initializable; with the ids specified in
project import javafx.scene.control.Button;
import javafx.scene.control.TextArea;
SceneBuilder

public class MyController implements Initializable {


@FXML
private Button sayHelloButton;
@FXML
private TextArea textHello;
@Override
public void initialize(URL location, ResourceBundle resources) {
}
public void sayHello(ActionEvent event) {
textHello.setText("Hello World");
}
}
95 96

95 96

24
Connect fxml file with controller Create JavaFX application, load fxml file
v Update file SayHello.fxml: add property fx:controller for import javafx.application.Application;
import javafx.fxml.FXMLLoader;
the VBox tag, refer to the MyController we have created import javafx.scene.Parent;
import javafx.scene.Scene;
(use the full name of the class) import javafx.stage.Stage;
<?xml version="1.0" encoding="UTF-8"?>
public class MyApplication extends Application {
@Override
<?import javafx.scene.control.Button?> public void start(Stage primaryStage) {
<?import javafx.scene.control.TextArea?> try {
// Read fxml file and create the interface
<?import javafx.scene.layout.VBox?> Parent root = FXMLLoader.load(getClass()
.getResource("/oop/hust/SayHello.fxml"));
<VBox prefHeight="192.0" prefWidth="371.0" primaryStage.setTitle("My Application");
xmlns="http://javafx.com/javafx/11.0.1" primaryStage.setScene(new Scene(root));
xmlns:fx="http://javafx.com/fxml/1" primaryStage.show();
fx:controller="oop.hust.MyController"> } catch(Exception e) {
<children> e.printStackTrace();
}
<Button fx:id="sayHelloButton" mnemonicParsing="false" }
onAction="#sayHello" text="Say Hello" />
<TextArea fx:id="textHello" prefHeight="173.0" prefWidth="162.0" /> public static void main(String[] args) {
launch(args);
</children> }
</VBox> }
97 98

97 98

Reference
v http://tutorials.jenkov.com/javafx/overview.html

99

99

25

You might also like