6
JavaFX
Paradigmas de Programação
LEI - ISEP
Java FX
q An API
included
in Java 7
for UI
developm
ent
q The
successor
of Java
Swing
Java Conceptual Diagram
https://docs.oracle.com/javase/8/docs/index.html
2
Luiz Faria / PPROG / LEI-ISEP 1
Reasons to choose JavaFX
q Rich internet cross platform application
§ Windows, Mac & Linux
q 100% Java APIs with millions of libraries
q Easy to develop even for beginners
q Drag and drop application
q Only uses Java language programming
q Rapid application development using
Netbeans and SceneBuilder
JavaFX Key Features
q FXML → MVC Pattern Support
q WebView (embed web pages within a JavaFX application, including
Javascript support)
q Built-in UI controls, CSS and Themes (Modena, Caspian, etc.)
q 3D Graphics Features (Shape3D)
q Multi-touch Support, Hi-DPI support, Rich Text Support
q Hardware-accelerated graphics (uses optimally the GPU)
q High-performance media engine (playback of web multimedia content)
q Self-contained application deployment model
q Support FXML: a XML-based declarative language to define the
structure of the user interface separated from the application code
Luiz Faria / PPROG / LEI-ISEP 2
Requirements
q IDE: Netbeans, Eclipse, …
q JDK 8 -> JavaFX 8 already included in
installer
q SceneBuilder 2.0
§ Installer for multiple OS:
http://www.oracle.com/technetwork/java/javafxs
cenebuilder-1x-archive-2199384.html
JavaFX Architecture
Luiz Faria / PPROG / LEI-ISEP 3
Anatomy of a JavaFX application
q Each JavaFX program must extend
the Application class – the main class of a
JavaFX program
q start() method is the main entry point of the
application - first method to be called
q A JavaFX application consists of
a Stage and a Scene …
Theatre metaphor
q JavaFX uses the metaphor of a theater to model
the graphics application
q A stage (defined by the javafx.stage.Stage class)
represents the top-level container (window)
q Individual controls (or components) are contained
in a scene (defined by
the javafx.scene.Scene class)
q An application can have more than one scenes,
but only one of the scenes can be displayed on
the stage at any given time
Luiz Faria / PPROG / LEI-ISEP 4
Theatre metaphor
q The contents of a scene is represented in a
hierarchical scene graph of nodes (defined
by javafx.scene.Node)
Theatre metaphor
q To construct the UI:
§ Prepare a scene graph
§ Construct a scene, with the root node of the scene graph
§ Setup the stage with the constructed scene
10
Luiz Faria / PPROG / LEI-ISEP 5
JavaFX Application Life Cycle
q A JavaFX application extends from javafx.application.Application
q The JavaFX runtime maintains an Application's life cycle as follows:
§ It constructs an instance of Application
§ It calls the Application's init() method
§ It calls the Application's start(javafx.stage.Stage) method, and passes the
primary stage as its argument
§ It waits for the Application to complete (e.g., via Platform.exit(), or closing
all the windows)
§ It calls the Application's stop() method
q The start() is an abstract method, that must be overridden;
The init() and stop() has default implementation that does nothing
q If you use System.exit(int) to terminate the application, stop() will not
be called
11
Stage
q A stage (defined by the javafx.stage.Stage class) represents the top-
level container, typically a window
q A stage is divided into decoration (title bar and border) and the content
area
q A stage can have one of these styles:
§ StageStyle.DECORATED: solid white background with decorations
§ StageStyle.UNDECORATED: solid white background with no decorations
§ StageStyle.TRANSPARENT: transparent background with no decorations
§ StageStyle.UTILITY: solid white background with minimal decorations
q A primary stage is created by the JavaFX runtime, and passed into
the Application as an argument in the Application's start() method
12
Luiz Faria / PPROG / LEI-ISEP 6
Scene and Scene Graph
q The contents of a scene is represented in a
hierarchical (tree-like) scene graph of nodes
q To construct a Scene, we need to pass the
root of the scene graph and optional width
and height
Scene(Parent root, double width, double height)
13
Nodes
q A node is defined by an abstract class javafx.scene.Node, which is the
superclass of all the UI elements:
§ Controls (Components): subclasses of Parent in package javafx.scene.control,
e.g., Label, TextField, Button
§ Layout Pane (Containers): subclasses of Parent in package javafx.scene.layout,
e.g., StackPane, FlowPane, GridPane, BorderPane
§ Geometrical Shapes: subclasses of Shape and Shape3D in
package javafx.scene.shape, e.g., Circle, Rectangle, Polygon, sphere, Box
§ Media Elements: e.g., ImageView, MediaView (playable by media player) in
packages javafx.scene.image and javafx.scene.media
§ …
14
Luiz Faria / PPROG / LEI-ISEP 7
Parents
q Parent (Branch Node): having
child nodes, defined by the
abstract
class javafx.scene.Parent with 3
concrete subclasses:
§ Group: Any transform (e.g. rotation),
effect, or state applied to a Group
will be applied to all children of that
group
§ Region: is the base class for all UI
Controls and layout
containers. Region has 4
subclasses: Control (UI
controls), Pane (Container), Chart (
PieChart, XYChart) and Axis.
§ WebView: for HTML content
15
Controls
16
Luiz Faria / PPROG / LEI-ISEP 8
How to develop a JavaFX application
q Programmatically
§ Designing a scene and placing controls using code can become
messy as the complexity grows
q FXML and Scene Builder
§ Rapid scene development / mock up using Scene Builder
§ FXML is not a compiled language; you do not need to recompile
the code to see the changes; just reload the FXML file
§ It provides a clear separation of GUI from logic/controller
§ So you can have different versions of a scene/view using the same
controller. This is handy for demo's for instance
§ The content of an FXML file can be localized as the file is read
§ But the FXML take some time to be loaded and needs to be
parsed
17
JavaFX Programmatically
import …
public class HelloWorld extends Application {
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) {
primaryStage.setTitle("Hello World!");
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);
primaryStage.setScene(new Scene(root, 300, 250));
primaryStage.show();
}
}
18
Luiz Faria / PPROG / LEI-ISEP 9
FXML and SceneBuilder
q Screen building using SceneBuilder which
generates FXML - Drag and Drop application for
Layout GUI
§ Layout containers
§ Place controls
§ Associate events Generates
§ Style FXML
q Map to a controller class Associates
Controller
19
MVC Pattern
q Helps to decouple data access and business logic
from the manner in which it is displayed to the
user
q Can be broken down into three elements:
§ Model - represents data and the rules that govern
access to and updates of this data
§ View - The view renders the contents of a model. It
specifies exactly how the model data should be
presented. If the model data changes, the view must
update its presentation as needed
§ Controller - The controller translates the user's
interactions with the view into actions that the model
will perform
20
Luiz Faria / PPROG / LEI-ISEP 10
MVC Pattern
1. After seeing it on
VIEW
2. Users use
CONTROLLER
3. Manipulate data
(Update, modify,
delete, ..), the
data on MODEL
has been
changed.
4. Displaying the
data of MODEL
on VIEW.
21
FXML
q XML-based language that provides the structure
for building a user interface separate from the
application logic of your code.
q FXML (Declarative)
<BorderPane>
<top>
<Button text=“Sign In”/>
</top>
Can be created by Scene Builder
<center>
<TextField/>
</center>
</BorderPane>
22
Luiz Faria / PPROG / LEI-ISEP 11
Using FXML to Create UI (1)
q FXML Loader
Parent root = FXMLLoader.load(
getClass().getResource(”Scene.fxml"));
Scene scene = new Scene(root, 300, 275);
q Create the link between view and control
<BorderPane fx:controller=“FXMLController”>
<top>
<Button text=“Sign In” onAction=
“#handleSubmitButtonAction”/>
</top>
<center>
<TextField fx:id=“actiontarget” />
</center>
</BorderPane>
23
Using FXML to Create UI (2)
q Define the code to handle events in the
controller class
public class FXMLExampleController implements Initializable {
@FXML
private TextField actiontarget;
@FXML
protected void handleSubmitButtonAction(ActionEvent event) {
actiontarget.setText("Sign in button pressed");
}
@Override
public void initialize(URL location, Resources resources){
}
}
24
Luiz Faria / PPROG / LEI-ISEP 12
Controller Class
q initialize() method – the controller class
implements Initializable interface
§ Called once the contents of its associated FXML
document have been completely loaded
q FXML tag
§ These annotation marks a protected or private class
member as accessible to FXML
§ In the previews controller class:
• First FXML tag: the Text field is annotated to allow the loader to
set its value
• Second FXML tag: allow the handler method
handleSubmitButtonAction() be called when a event
occurs on the Button
25
Controller Class
q Contains event handlers
q Each FXML can have only one controller
class
§ However, a FXML file can include other FXML
files (via the <fx:include> element) and each
of them can have its own controller
§ Controller instances for nested FXML
documents loaded via
the <fx:include> element are mapped
directly to member fields of the including
controller (to be seen further ahead)
26
Luiz Faria / PPROG / LEI-ISEP 13
Components in JavaFX
q Containers
§ Accordion, Anchor Pane, Stack Pane, Tab Pane, Grid
Pane, Hbox, Vbox, …
q Controls
§ Button, Choice box, Combo box, ImageView, WebView,
TextField, TextArea, Label, …
q Shapes
§ Rectangle, Circle, Arc, Ellipse, Line, Polygon, Text,
Cubic Curve
q Charts
§ Area chart, Bar chart, Scatter Chart, Pie chart, Bubble
chart
27
Layout Panes (Containers) (1)
q Layout panes are containers which are used for flexible
and dynamic arrangements of UI controls within a scene
graph of a JavaFX application
q As a window is resized, the layout pane automatically
repositions and resizes the nodes it contains
28
Luiz Faria / PPROG / LEI-ISEP 14
Layout Panes (Containers) (2)
q JavaFX built-in layout panes:
§ FlowPane – lays out its children in a flow that wraps at the
flowpane's boundary.
§ HBox – arranges its content nodes horizontally in a single row.
§ VBox – arranges its content nodes vertically in a single column.
§ AnchorPane – anchor nodes to the top, bottom, left side, or center
of the pane.
§ BorderPane – lays out its content nodes in the top, bottom, right,
left, or center region.
§ StackPane – places its content nodes in a back-to-front single
stack.
§ TilePane – places its content nodes in uniformly sized layout cells
or tiles.
§ GridPane – places its content nodes in a grid of rows and columns.
29
Layout Panes (Containers) (3)
§ FlowPane – lays out its child components either vertically or
horizontally, and which can wrap the components onto the next
row or column if there is not enough space in one row
§ HBox – arranges its content nodes horizontally in a single row;
controls are kept on the same horizontal row even if there is not
enough space to show them in their fully preferred widths
30
Luiz Faria / PPROG / LEI-ISEP 15
Layout Panes (Containers) (4)
§ VBox – arranges its content nodes vertically in a single column
31
Layout Panes (Containers) (5)
§ BorderPane – pane divided into 5 separate areas, each of area
can contain a subcomponent
• Top/Bottom area: Can shrink/expand horizontally and keep the height
unchanged.
• Left/Right area: Can shrink/expand vertically and keep the length unchanged.
• Center area: Can shrink/expand in both directions
32
Luiz Faria / PPROG / LEI-ISEP 16
Layout Panes (Containers) (6)
§ AnchorPane – similar to BorderPane. BorderPane is divided into 5
separate areas in order to place subcomponent on
while AnchorPane is divided into 5 areas in order to anchor on; A
subcomponent can be anchored into one or more logic areas
of AnchorPane
33
Layout Panes (Containers) (7)
§ StackPane – contains different components, subcomponents
stacked up to others, and at a certain moment, you can only see
the subcomponent lying on the top of Stack
34
Luiz Faria / PPROG / LEI-ISEP 17
Layout Panes (Containers) (8)
§ TilePane – lays out its child components in a grid of equally sized
cells
§ GridPane – lays out its child components in a grid; the size of the
cells in the grid depends on the components displayed in the
GridPane; all cells in the same row will have the same height, and
all cells in the same column will have the same width; different
rows can have different heights and different columns can have
different widths
35
Example 1 – Font Viewer
36
Luiz Faria / PPROG / LEI-ISEP 18
Creating a Maven/JavaFX
project in NetBeans
File -> New Project…->Maven->JavaFX Application
37
Editing the fxml file in
SceneBuilder
Over the fxml file select Open
38
Luiz Faria / PPROG / LEI-ISEP 19
Defining the GUI layout in
SceneBuilder
39
Defining property values for
the controls
40
Luiz Faria / PPROG / LEI-ISEP 20
Define the values of fx:id
property of controls in SB
In Code tab:
41
Define the event handler
method name for the control
In Code tab:
42
Luiz Faria / PPROG / LEI-ISEP 21
Define the name of the
controller class
43
Save the fxml file in SB
q The fxml file is updated
q It is possible to edit this file in NetBeans
44
Luiz Faria / PPROG / LEI-ISEP 22
Open controller class in
NetBeans
Add FXML tags to control references
When the controller is instantiated, attributes marked with
FXML tag will be initialized with the control references
45
Add the code to event
handlers
46
Luiz Faria / PPROG / LEI-ISEP 23
setLabelFont() method
47
Initialize() method
This method is defined in Initializable interface and is called when the
controller object is created
48
Luiz Faria / PPROG / LEI-ISEP 24
JavaFX application main class
49
JavaFX application main class
q All subclasses of the Application class must implement the
abstract start()
q The start() method is called when the JavaFX
application is started
q The start() method takes a single parameter of the
type Stage
§ The Stage is where all the visual parts of the JavaFX application
are displayed
§ The Stage object is created for you by the JavaFX runtime
q The main() method isn’t mandatory
§ Use when you need to pass command line parameters to the
application
§ The launch static method launches the JavaFX runtime and the
JavaFX application
50
Luiz Faria / PPROG / LEI-ISEP 25
Example: nested controllers
q In this example we will see how several controllers
communicate
§ Their communication is done through a MainController which act
as a mediator
§ Each individual controller only knows how to communicate with the
MainController
51
Example: nested controllers
q The GUI will have two tabs – each tab has its own
controller
§ These controllers can communicate with one another
through the MainController
§ Each controller is responsible for its own tab, but they
can also send or request information via MainController
– the code becomes easier to maintain and
dependencies are minimal
52
Luiz Faria / PPROG / LEI-ISEP 26
Example: nested controllers
q In Tab1:
§ Save button will act only inside of its own tab
§ The other button (send) will be used for communication
with the other tab through MainController class
§ Clicking on [Save text] button will set the value from
TextField to Label; after that we will use the other
button to send the text in the label across the
MainController to the other tab
53
Example: nested controllers
q In Tab2:
§ Save button will act only inside of its own tab
§ The other button (load) will be used for communication
with the other tab through MainController class
§ Clicking on [Save text] button will set the value from
TextField to Label; after that we will use the other
button to load the text from the label in Tab1 across the
MainController to the label in Tab2
54
Luiz Faria / PPROG / LEI-ISEP 27
Example: nested controllers
q We will use 3 FXML files
§ One for each Tab: Tab1.fxml and Tab2.fxml
§ The main FXML will include the other two
FXML files: Main.fxml
Main.fxml
Tab1.fxml
Tab2.fxml
55
Example: nested controllers
q In Main.fxml:
§ We have to manually add an fx:id property to all includes – It is
important that the id has the same name as the fxml file, only with
lower first letter
56
Luiz Faria / PPROG / LEI-ISEP 28
Example: nested controllers
q In Tab1.fxml
57
Example: nested controllers
q In MainController.java
§ Variable names for the controller have to be identical the controller name;
the first letter must be in lower case (tab1Controller, tab2Controller)
§ In the initialize method we will be passing [this] as a parameter to every
controller so that the controllers have a way of calling methods on
MainController
58
Luiz Faria / PPROG / LEI-ISEP 29
Example: nested controllers
q Tab1Controller.java
59
Example: nested controllers
q Tab2Controller.java
60
Luiz Faria / PPROG / LEI-ISEP 30
Resources
q JavaFX website: http//javafx.com
q JavaFX API
https://docs.oracle.com/javase/8/javafx/api/toc.htm
q Open source project
http://openjdk.java.net/projects/openjfx/
q Oracle Premier Support for Software
http://www.oracle.com/us/support/software/premier/
q Blogs
§ http://fxexperience.com
§ http://blogs.oracle.com/javafx
61
Luiz Faria / PPROG / LEI-ISEP 31