10-JavaFX
10-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
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;
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
Nhập vào:
http://download.eclipse.org/efxclipse/updates-
released/3.0.0/site
15 16
15 16
4
e(fx)clipse installment e(fx)clipse installment
17 18
17 18
19 20
19 20
5
Add JavaFX Scene Builder to Eclipse Add JavaFX Scene Builder to Eclipse
21 22
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
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
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
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");
37 38
37 38
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();
//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");
41 42
41 42
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
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
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
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
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
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
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
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
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
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
83 84
21
Example Example
v When click on the circle v When click on Button
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
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
91 92
91 92
23
Specify button properties Specify button properties
93 94
93 94
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