Introduction to JavaFX GUI Programming
Introduction to JavaFX GUI Programming
By Muluken W.
1
GUI Applications
So far, you’ve probably only worked on console
applications
Provide input from keyboard
Read input using [Link]
Do something
Print result to [Link]
It’ll be nice to have a GUI application
Examples: Microsoft Word, Apps on your phone,
Your browser
We cover the basic material before covering GUI
programming because it requires use of all the
basic knowledge you’ve learned so far
2
GUI Applications
8
JavaFX
JavaFX is a Java library used to build Rich Internet
Applications.
The applications written using this library can run
consistently across multiple platforms.
The applications developed using JavaFX can run on
various devices such as Desktop Computers, Mobile
Phones, TVs, Tablets, etc..
Need for 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 includes all these features in a single library.
In addition to these, the developers can also access the
existing features of a Java library such as Swings.
9
Features of JavaFX
Let see some of the important features of JavaFX −
Written in Java − The JavaFX library is written in Java
and is available for the languages that can be executed on
a JVM, which include − Java, Groovy and JRuby. These
JavaFX applications are also platform independent.
FXML − JavaFX features a language known as FXML,
which is a HTML like declarative markup language. The
sole purpose of this language is to define a user Interface.
Scene Builder − JavaFX provides an application named
Scene Builder.
On integrating this application in IDE’s such as Eclipse
11
… Features of JavaFX
Rich set of API’s − JavaFX library provides a rich set of API’s
to develop GUI applications, 2D and 3D graphics, etc.
Using this API, you can access the features of Java
12
… Features of JavaFX
GWT (Glass Windowing Toolkit)
As the name suggests, GWT provides
services to manage Windows, Timers,
Surfaces and Event Queues. GWT connects
the JavaFX Platform to the Native Operating
System.
13
JavaFX provides a complete API with a rich set of
classes and interfaces to build GUI applications
with rich graphics.
The important packages of this API are −
1. [Link] − Contains classes to add transition based
animations such as fill, fade, rotate, scale and translation, to the
JavaFX nodes.
2. [Link] − Contains a set of classes responsible for the
JavaFX application life cycle such as: Init(), start(), stop() method.
3. [Link] − Contains classes to add CSS–like styling to JavaFX GUI
applications.
4. [Link] − Contains classes and interfaces to deliver and
handle JavaFX events.
5. [Link] − Contains classes to define 2D and 3D such as
circle, rectangle, polygon, etc. and perform operations on them.
6. [Link] − This package holds the top level container classes
for JavaFX application.
7. [Link] − This package provides classes and interfaces to
support the scene graph.
14
Scene Graph
It provides sub-packages such as canvas, chart, control, effect,
image, input, layout, media, paint, shape, text, transform, web, etc.
In JavaFX, the GUI Applications were coded using a 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 − (2D and 3D) such as
etc.
Containers − (layout panes) such as Border Pane, Grid Pane,
15
… Scene Graph
Each node in the scene graph has a single parent, and the
node which does not contain any parents is known as the root
node.
In the same way, every node has one or more children, and
the node without children is termed as leaf node; a node with
children is termed as a branch node.
A node instance can be added to a scene graph only once. The
nodes of a scene graph can have Effects, Opacity, Transforms,
Event Handlers, Event Handlers, Application Specific States.
A Group class is the subclass of Node, whose purpose is to
group several node objects in to a single act.
A Canvas class is basically a Node subclass which provides an
API to draw shapes using a set of graphics commands.
The advantage of Canvas is that we can obtain its
GraphicsContext and invoke drawing operations to render
custom shapes onscreen.
16
WebView
Using JavaFX, you can also embed HTML content in
to a scene graph. WebView is the component of
JavaFX which is used to process this 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.
17
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.
The JavaFX media engine provides support for audio for
the following file formats −
The package [Link] contains the classes
and interfaces to provide media functionality in JavaFX.
It is provided in the form of three components, which
are − •MP3
Audio •WAV
•AIFF
Becomes:
import [Link];
…
public class MyProgram extends Application
{
// Body of class
}
20
JavaFX HelloWorld Example: Start
public class HelloWorld extends Application {
public static void main(String[] args) {
launch(args);
}
22
import [Link];
import [Link];
import [Link];
import [Link];
public class MultipleStageDemo extends Application
{
@Override // Override the start method in the Application
class
public void start(Stage primaryStage)
{ // Create a scene and place a button in the scene
Scene scene = new Scene(new Button("OK"), 200, 250);
[Link]("MyJavaFX"); // Set the stage title
[Link](scene); // Put the scene in the
stage
[Link](); // Display the stage
Stage stage = new Stage(); // Create a new stage
[Link]("Second Stage"); // Set the stage title
// Set a scene with a button in the stage
[Link](new Scene(new Button("New Stage"), 100,
100));
[Link](); // Display the stage
}} 23
Default stages
By default, stages (windows) are resizeable.
Note that we have minimize and maximize buttons
If we want our stage to be of fixed size (i.e., not
resizeable),
we can set that property with
[Link](false)
24
We can put the button directly on the scene,
which centered the button and made it occupy
the entire window.
Rarely is this what we really want to do
One approach is to specify the size and location
of each UI element (like the buttons)
A better solution is to
put the UI elements
(known as nodes)
into containers called
panes, and then add
the panes to the scene.
25
Panes can even contain other panes:
26
Layout Panes
JavaFX provides many types of panes for organizing
nodes in a container.
As we’ve said (and have been doing), we add our
Nodes to a Pane, and then add the Pane to a Scene,
and then the Scene to a Stage (probably the primary
stage).
How do we arrange (i.e., lay out) the Nodes on the
pane?
Java has several different kinds of Panes that do a lot
of the layout work for us.
This section examines these layout panes in more
detail
We’ve already used the Pane , HBox, and StackPane;
we’ll start with the FlowPane…
27
Layout Panes…
Name Description
Pane Base class for layout panes. Use its getChildren()
method to return the list of nodes on the pane (or
add to that list)
Provides no particular layout capabilities – it’s a
“blank canvas” typically used to draw shapes on
StackPane Places nodes on top of each other in the center of the
pane
FlowPane Places the notes row-by-row horizontally or column-
by-column vertically (reading order)
GridPane Provide a 2-D grid of cells, into which we can place
nodes
BorderPan Divides pane into top, bottom, left, right, and center
e regions
HBox Places nodes in a single (horizontal) row
VBox Places nodes in a single (vertical) column 28
FlowPane
The FlowPane can be set up to work in
“reading order” (sequential rows left-to-right),
by using [Link] or in
sequential top-to-bottom columns
([Link])
You can also specify the gap between nodes
(in pixels)
So far, we have seen putting Button nodes on
a pane.
uses the FlowPane and Label & TextField
nodes.
Let’s take a closer look… 29
FlowPane …
public void start(Stage primaryStage) // From Listing 14.10 (p. 553)
{
// Create a pane and set its properties
FlowPane pane = new FlowPane();
[Link](new Insets(11, 12, 13, 14));
[Link](5);
[Link](5);
35
GridPane
The GridPane divides the pane’s area into a 2-
D grid of rows and columns.
The previous example redone, with the three
Labels in the left column, and the three
TextFields (note that the author did not bother
to make the MI TextField narrow in this
example)
36
The BorderPane
37
HBox and VBox
HBoxThe HBox layout arranges all the nodes in our
application in a single horizontal row.
The class named HBox of the
package [Link] represents the text
horizontal box layout.
VBoxThe VBox layout arranges all the nodes in our
application in a single vertical column.
The class named VBox of the
package [Link] represents the text
Vertical box layout.
38
Frequently Used UI Controls
39
A text field can be used to
enter or display a string.
Radio buttons, also
known as option buttons,
enable you to choose a
single item from a group of
choices. In appearance
radio buttons resemble
check boxes, but check
boxes display a square
that is either checked or
blank,
A buttonwhereas radio that
is a control
buttons
triggers display
an action a circle
event A CheckBox is used for the
that
whenisclicked.
either filled
JavaFX(if user to make a selection. Like
selected) or blankbuttons,
(if not Button, CheckBox inherits all
provides regular the properties such as
selected).
toggle buttons, check box onAction, text, graphic,
buttons, and radio buttons. alignment, graphicTextGap,
The common features of textFill, contentDisplay from40
UI Controls … ScrollBar
A scroll bar is a control that enables the user to select from a range of
values. The scrollbar appears in two styles: horizontal and vertical.
Scroll Bar
Properties
42
UI Controls … ListView
43
UI Controls … Sliders
Slider is similar to ScrollBar, but Slider has more
properties and can appear in many forms.
Rewrite the preceding
program using the
sliders to control a
message displayed
on a panel instead of
using scroll bars.
44
Datepicker
45
The Image & ImageView Classes
46
The Image & ImageView Classes
public class image extends Application {
@Override
public void start(Stage stage) throws FileNotFoundException {
//Creating an image
Image image = new Image(new FileInputStream("C:\\Users\\
Abuyasmin\\Desktop\\save_spend\\[Link]"));
ImageView imageView = new ImageView(image);
[Link](200); // fit into 200-x-200
[Link](200);
//Creating a Group object
Group root = new Group(imageView);
//Creating a scene object
Scene scene = new Scene(root, 600, 500);
//Setting title to the Stage
[Link]("image ");
//Adding scene to the stage
[Link](scene);
//Displaying the contents of the stage
[Link]();
}
47
JavaFX | MenuBar and Menu
MenuBar is usually placed at the top of the
screen which contains several menus.
Menu is a popup menu that contains several
menu items that are displayed when the user
clicks a menu.
The user can select a menu item after which the
menu goes into a hidden state.
48
Example of MenuBar and
Menu
public void start(Stage s)
{
[Link]("creating MenuBar"); // set title for the stage
MenuItem m1 = new MenuItem("menu item 1"); // create
menuitems
MenuItem m2 = new MenuItem("menu item 2");
MenuItem m3 = new MenuItem("menu item 3");
Menu m = new Menu("Menu"); // create a menu
[Link]().add(m1); // add menu items to menu
[Link]().add(m2);
[Link]().add(m3);
MenuBar mb = new MenuBar(); // create a menubar
[Link]().add(m); // add menu to menubar
VBox vb = new VBox(mb); // create a VBox
Scene sc = new Scene(vb, 500, 300); // create a scene
[Link](sc); // set the scene
[Link](); }
49
Shapes
JavaFX provides many shape classes for drawing texts, lines,
circles, rectangles, ellipses, arcs, polygons, and polylines.
52
Shapes… Rectangle
The Rectangle shape is specified by its top-left
corner (x, y) and its width and height.
Optionally, we can specify the arcWidth and
arcHeight (in pixels) of the corners, to create
rounded corners (arc measurements of 0
make
squared-off corners)
53
Shapes… Circle and Ellipse
54
Shapes… Arc
An Arc is just part of an Ellipse
An Arc is specified by its center point, radii,
start angle (in degrees), and length (in
degrees)
If the two radii are equal, then it’s a circular
arc
Angles may be negative (clockwise sweep)
55
Shapes… Polygon and Polyline
56
Shapes… Polygon and Polyline
57
Shapes… Polygon and Polyline
Pane pane = new Pane(); // create a pane
Polygon polygon = new Polygon(); // create a polygon
[Link]().add(polygon); // add the polygon to the pane
[Link]([Link]); // polygon will be filled in white
[Link]([Link]); // with a black border
ObservableList<Double> list = [Link](); // get its vertex
list
MediaPlayer
The MediaPlayer class playes and controls the media with properties such as
autoPlay, currentCount, cycleCount, mute, volume, and totalDuration.
MediaView
The MediaView class is a subclass of Node that provides a
view of the Media being played by a MediaPlayer. The
MediaView class provides the properties for viewing the media.
59
Example: Using Media
This example displays
a video in a view. You
can use the play/pause
button to play or pause
the video and use the
rewind button to
restart the video, and
use the slider to control
the volume of the
audio.
60
JavaFX Events
Clicking on a button usually triggers an event. For example,
clicking the print button on the print dialog we meant to print
a document to printer. UI library uses the events to notify
something happened.
JavaFX event is an instance of the [Link] class or its subclass.
JavaFX provides several events, including
ActionEvent
InputEvent
ScrollToEvent
SortEvent
MediaErrorEvent
[Link]
TransformChangedEvent
WindowEvent
WorkerStateEvent
WebEvent
61
Events…
You can define your own event by extending the
Event class.
The following table lists properties from Event
Property Description
Type of event that occurred. For example, mouse
type
event.
Source Origin of the event.
Target Last Node in the event dispatch chain.
An event type is an instance of the EventType class.
For example, the KeyEvent class contains the
following event types:
KEY_PRESSED
KEY_RELEASED
KEY_TYPED
62
Event-type vs Event-Class
Event-type is the type of event that the handler
processes, for example, setOnKeyTyped for Key Typed
events or setOnMouseClicked for Mouse Clicked events.
event-class is the class that defines the event type, for
[Link](new EventHandler<ActionEvent>() {
public void handle(ActionEvent event) {
[Link]("Hello World"); } });
63
Key Event
64
Mouse Events
65
Gesture and Touch Events
JavaFX can handle events from Touch-
Enabled Devices for touches and gestures.
Gesture Description
Triggered when using two-finger to rotate objects. It fires the
following event
Rotate •ROTATION_STARTED
•ROTATE
•ROTATION_FINISHED
Sliding movement. If a mouse wheel is used for scrolling, only
the events of type SCROLL are generated. It fires the following
events:
Scroll
•SCROLL_STARTED
•SCROLL
•SCROLL_FINISHED
•Sweeping movement across the screen. It fires the following
events: SWIPE_LEFT
Swipe •SWIPE_RIGHT
•SWIPE_UP
•SWIPE_DOWN
•Zoom by two-finger. It fires the following events:
ZOOM_STARTED
Zoom
•ZOOM 66
e.g. rotate and scroll
67
e.g. Swipe and zoom
68
e.g. Touch screen
69
Drag drop
70
71
what is the difference between
Event-type and Event-Class?
72
Theme
JavaFX application support theme through CSS settings.
Theming can transforming an entire application's appearance without
changing its functionality.
In JavaFX you have the ability to create, modify, or use existing
themes to skin your applications.
Application Theme
The setUserAgentStylesheet(String URL) method accepts a valid URL
string representing the JavaFX CSS file.
CSS files are bundled inside a jar application or they can reside on the
local file system or a remote web server.
The setUserAgentStylesheet() method applies styling globally to all
scenes owned by an application.
To load the CSS file from the classpath, call
getClass().getResource("path/some_file.css").toExternalForm()
method. It will find the CSS file and produce a URL String.
The [Link] file and Java class are in the same directory, so there
is no need for a path in front of the file name.
73
JavaFX WebEngine
74
WebEngine
77
Communicating from Java to
JavaScript
79
JavaFX WebView
80
WebEvents
In the event handler we can decide if to show
a dialog.
The following table shows the events and
83
Using CSS to change WebView
background
84