Mastering JavaFX 10

4.3 (3 reviews total)
By Sergey Grinev
    Advance your knowledge in tech with a Packt subscription

  • Instant online access to over 7,500+ books and videos
  • Constantly updated with 100+ new titles each month
  • Breadth and depth in over 1,000+ technologies
  1. Stages, Scenes, and Layout

About this book

JavaFX 10 is used to create media-rich client applications. This book takes you on a journey to use JavaFX 10 to build applications that display information in a high-performance, modern user interface featuring audio, video, graphics, and animation.

Mastering JavaFX 10 begins by introducing you to the JavaFX API. You will understand the steps involved in setting up your development environment and build the necessary dependencies. This is followed by exploring how to work with the assets, modules, and APIs of JavaFX. This book is filled with practical examples to guide you through the major features of JavaFX 10. In addition to this, you will acquire a practical understanding of JavaFX custom animations, merging different application layers smoothly, and creating a user-friendly GUI with ease.

By the end of the book, you will be able to create a complete, feature-rich Java graphical application using JavaFX.

Publication date:
May 2018


Stages, Scenes, and Layout

During the last decade, user interfaces have evolved beyond the capabilities of the old Java technologies. Modern users want to work with visually appealing applications and are used to the rich user interfaces brought by Web 2.0 and smartphones.

To address that, JavaFX was envisioned and added to Java a few releases ago. It was created from scratch to avoid any backward compatibility issues, and with a great understanding of the needs of modern user interfaces.

In this book, we will review the most important JavaFX APIs and will look into resolving some of the most common problems that JavaFX developers face, based on my development experience and over 500 questions I've answered in the JavaFX section of

In the first chapter, we will start with the backstage of a JavaFX application, including its windows and content area, and see which API is responsible for each of these main building blocks:

  • Application: This handles the application workflow, initialization, and command-line parameters
  • Stage: The JavaFX term for the window
  • Scene: This is the place for the window's content
  • SceneGraph: The content of the Scene

At the end of the chapter, we will create a clock demo that will demonstrate the concepts from this chapter.


Application and JavaFX subsystems

The very first API, javafx.application.Application, represents the program itself. It prepares everything for us to start using JavaFX and is an entry point for all standalone JavaFX applications. It does the following:

  • Initializes JavaFX toolkit (subsystems and native libraries required to run JavaFX)
  • Starts JavaFX Application Thread (a thread where all UI work happens) and all working threads
  • Constructs the Application instance (which provides a starting point for your program) and calls the user-overridden methods
  • Handles application command line parameters
  • Handles all cleanup and shutdown once the application ends

Let's look closely at each of these steps.

Components of the JavaFX toolkit

JavaFX toolkit is the stuff hidden under the hood of the JavaFX. It's a set of native and Java libraries that handles all the complexity of the drawing UI objects, managing events, and working with various hardware. Luckily, they are well-shielded by the API from the user. We will have a brief overview of the major components. It can be useful, for example, during debugging your application; by knowing these component names, you will be able to identify potential problems from stack traces or error messages.

Glass toolkit

This toolkit is responsible for low-level interaction with operating systems. It uses native system calls to manage windows, handle system events, timers, and other components.

Note that Glass is written from scratch; it doesn't use AWT or Swing libraries. So, it's better to not mix old Swing/AWT components and JavaFX ones for the sake of performance.

Prism and Quantum Toolkit

Prism renders things. It was optimized a lot over the course of JavaFX releases. Now, it uses hardware acceleration and software libraries available in the system such as DirectX or OpenGL. Also, Prism renders concurrently and also can render upcoming frames in advance while current frames are being shown, which gives a large performance advantage.

Quantum Toolkit manages the preceding Prism, Glass, and JavaFX API and handles events and rendering threads.


This framework is responsible for video and audio data. In addition to playback functionality, JavaFX Media provides advanced functionality—for example, buffering, seeking, and progressive downloading.

For better performance, Media uses the separate thread, which is synchronized with frames, prepared by Prism, to show/play relevant media data using the correct framerate.


WebView is a web rendering engine based on the OpenSource WebKit engine, it supports the majority of modern HTML features.

Using WebView, you can incorporate any web resources or even whole sites into your JavaFX applications and integrate them with modern web tools, such as Google Maps.

Working with JavaFX Application Thread

Despite the development of the technology, building a thread-safe UI toolkit is still an enormous challenge due to the complexity of the events and state handling. JavaFX developers decided to follow Swing pattern, and instead of fighting endless deadlocks proclaimed that everything in the UI should be updated from and only from a special thread. It's called JavaFX Application Thread.

For simple programs, you don't notice this requirement, as common JavaFX program entry points are already run on this thread.

Once you started adding multithreading to your application, you will need to take care of the thread you use to update the UI. For example, it's a common approach to run a lengthy operation on the separate thread:

new Thread(() -> {
//read myData from file
root.getChildren().add(new Text(myData));

This code tries to access JavaFX UI from a common Thread, and it will lead to:

java.lang.IllegalStateException: Not on FX application thread

To address that, you need to wrap your JavaFX code in the next construction:

Platform.runLater(()-> {
root.getChildren().add(new Text("new data"));
Note that you can not construct UI objects on JavaFX Application Thread. But, once you have showed them to the user you need to follow the JavaFX UI Thread rule.

Also, note that having one thread for the update UI means that while you run your code on this thread nothing is being updated, and the application looks frozen for the user. So, any long computational, network, or file-handling tasks should be run on a regular thread.

If you need to check in your code which thread you are on, you can use the following API:

boolean Platform.isFxApplicationThread();

Application class

The most common way to use the JavaFX API is to subclass your application from the javafx.application.Application class. There are three overridable methods in there:

  • public void init(): Overriding this method allows you to run code before the window is created. Usually, this method is used for loading resources, handling command-line parameters, and validating environments. If something is wrong at this stage, you can exit the program with a friendly command-line message without wasting resources on the window's creation.
Note this method is not called on JavaFX Application Thread, so you shouldn't construct any objects that are sensitive to it, such as Stage or Scene.
  • public abstract void start(Stage stage): This is the main entry point and the only method that is abstract and has to be overridden. The first window of the application has been already prepared and is passed as a parameter.
  • public void stop(): This is the last user code called before the application exits. You can free external resources here, update logs, or save the application state.

The following JavaFX code sample shows the workflow for all these methods:

Note the comment in the first line—it shows the relative location of this code sample in our book's GitHub repository. The same comment will accompany all future code samples, for your convenience.
// chapter1/
import javafx.application.Application;
import javafx.scene.*;
import javafx.stage.Stage;

public class FXApplication extends Application {

public void init() {

public void start(Stage stage) {
Scene scene = new Scene(new Group(), 300, 250);
stage.setTitle("Hello World!");

public void stop() {

Note that you don't need the main() method to run JavaFX. For example, this code can be compiled and run from the command line:

> javac
> java FXApplication

It shows a small empty window:

Using the Application.launch() method

If you need to have control over the moment JavaFX starts, you can use the Application.launch() method:

public static void main(String[] args) {
// you custom code
Application.launch(MyApplication.class, args);

Here, MyApplication should extend javafx.application.Application.

Managing command-line parameters

Unlike the regular Java programs, which receive all parameters in the main(String[] args) method, JavaFX provides an extra API to get them: Application.getParameters(). Then, you can access them next categories:

  • raw format: without any changes
  • parsed named pairs: only parameters which were formatted as Java options: --name=value. They will be automatically built into a name-value map.
  • unnamed: parameters which didn't fit into the previous category.

Let's compile and run a program with next demo parameters (run these commands from Chapter1/src folder of book's GitHub repository):

java FXParams --param1=value1 uparam2 --param3=value3

This will run next code, see the corresponding API calls in bold:

System.out.println("== Raw ==");
System.out.println("== Unnamed ==");
System.out.println("== Named ==");
getParameters().getNamed().forEach((p, v) -> { System.out.println(p + "=" +v);});

JavaFX will parse these parameters and allocated them into categories:

== Raw ==
--param3=value 3
== Unnamed ==
== Named ==
param3=value 3

Closing the JavaFX application

Usually, the JavaFX application closes once all of its windows (Stages) are closed.

You can close the application at any moment by calling javafx.application.Platform.exit().

Don't call System.exit() as you may be used to doing in Java programs. By doing that you break the JavaFX application workflow and may not call important logic written in on close handlers such as Application.stop().

If you don't want your application to automatically close, add the following code at the beginning of your program:


Stage – a JavaFX term for the window

Every UI app needs a window. In JavaFX, the javafx.stage.Stage class is responsible for that. The very first stage/windows are prepared for you by Application and your usual entry point for the app is method start, which has Stage as a parameter.

If you want to have more windows, just create a new Stage:

Stage anotherStage = new Stage();;

Working with Stage modality options

Modality determines whether events (for example, mouse clicks) will pass to an other application's windows. This is important as you would then need to show the user a modal dialog style window or a warning, which should be interacted with before any other action with the program.

Stage supports three options for modality:

  • Modality.NONE: The new Stage won't block any events. This is the default.
  • Modality.APPLICATION_MODAL: The new Stage will block events to all other application's windows.
  • Modality.WINDOW_MODAL: The new Stage will block only events to hierarchy set by initOwner() methods.

These options can be set by calling the Stage.initModality() method.

The following sample shows how it works. Try to run it and close each window to check events handling, and see the comments inline:

// chapter1/
public class FXModality extends Application {

public void start(Stage stage1) {
// here we create a regular window
Scene scene = new Scene(new Group(), 300, 250);
stage1.setTitle("Main Window");

// this window doesn't block mouse and keyboard events
Stage stage2 = new Stage();
stage2.setTitle("I don't block anything");

// this window blocks everything - you can't interact
// with other windows while it's open
Stage stage3 = new Stage();
stage3.setTitle("I block everything");

// this window blocks only interaction with it's owner window (stage1)
Stage stage4 = new Stage();
stage4.setTitle("I block only clicks to main window");

Using Stage styles

Stage style is the way your window is decorated outside of the Scene.

You can control how Stage will look using StageStyle enum values. It can be passed to the constructor or through the initStyle() method:

// chapter1/StageStylesDemo
Stage stage = new Stage(StageStyle.UNDECORATED)
// or

See the existing options in the following figure. Note that a Windows screenshot was used here, but decorations will look different on other operating systems because they are a part of the OS user interface and not drawn by Java or JavaFX.

Setting fullscreen and other window options

There are several other options to manipulate Stage that are self-explanatory, like in the following examples:


The only unusual thing about this API is the extra fullscreen options—you can set up a warning message and key combination to exit fullscreen using the following methods:

 primaryStage.setFullScreenExitHint("Exit code is Ctrl+B");

Note the convenient KeyCombination class, which can parse names of shortcuts. If you prefer more strict methods, you can use KeyCodeCombination instead:

KeyCodeCombination kc = new KeyCodeCombination(KeyCode.B, KeyCombination.CONTROL_DOWN);

Scene and SceneGraph

Every element of the JavaFX Scene is a part of the large graph (or a tree, strictly speaking) that starts from the root element of the Scene. All these elements are represented by the class Node and its subclasses.

All SceneGraph elements are split into two categories: Node and Parent. Parent is Node as well, but it can have children Node objects. Thus, Node objects are always leaves (endpoints of the SceneGraph), but Parent objects can be both leaves and vertices depending on whether they have children or not.

Parent objects generally have no idea what kind of Node objects their children are. They manage only direct children and delegate all further logic down the graph.

This way, you can build complex interfaces from smaller blocks step by step, organize UI elements in any way, and quickly change the configuration on the higher levels without modifying the lower ones.

Let's take a look at the next short JavaFX application, which shows a window with a checkbox and a gray background:

Take a look at the following code snippet:
public class HelloFX extends Application {
public void start(Stage stage) {
StackPane root = new StackPane();

CheckBox node = new CheckBox("I'm ready for FX!");
Rectangle rect = new Rectangle(70, 70, Color.GREEN);
root.getChildren().addAll(rect, node);

Scene scene = new Scene(root, 150, 100);
stage.setTitle("Hello FX!");;

From the code, the scenegraph here looks like this:

But, CheckBox itself consists of several nodes, and by digging deeper you can see that it looks like this:

You can always check the scenegraph structure by traversing the graph, starting from the Scene root. Here is a convenient method that prints the scenegraph and indents each parent:

 public void traverse(Node node, int level) {
for (int i = 0; i < level; i++) {
System.out.print(" ");
if (node instanceof Parent) {
Parent parent = (Parent) node;
parent.getChildrenUnmodifiable().forEach(n->traverse(n, level +1));

For our HelloFX example, it will provide the following output:

class javafx.scene.layout.StackPane
class javafx.scene.shape.Rectangle
class javafx.scene.control.CheckBox
class javafx.scene.layout.StackPane
class javafx.scene.layout.StackPane

Organizing the Scene content with Layout Managers

In this section, we will review various Layout Managers that control how your nodes are organized on a Scene.

Layout Managers don't have much UI by themselves; usually, only the background and borders are visible and customizable. Their main role is to manage their children nodes.

Free layout

The following managers don't relocate or resize your nodes at all: Pane, Region, and Group. You set coordinates for each of your nodes manually. You can use these layout managers when you want to set absolute positions for each element, or when you want to write your own layout logic.

Let's review the difference between these free layout managers.

The most basic layout manager – Group

Group is a very lightweight layout manager. It doesn't support a lot of customizing options (for example, background color) and doesn't have any size control—Group's size is a combination of child sizes, and anything too large will be trimmed.

So, unless you need to have a huge amount of components and care a lot about performance, consider using another manager.

Region and Pane layout managers

Region and Pane support the whole range of styles and effects. They are used as a basis for almost all JavaFX UI components.

The only difference between them is an access level to their children's list.

Pane gives the public access to the getChildren() method. So, it's used as an ancestor to layout managers and controls which API allows the manipulating of children.

Region, on the other hand, doesn't allow changing its children list. getChildren() is a private method, so the only way to access them is Region.getChildrenUnmodifiable(), which doesn't allow you to change the list. This approach is used when a component is not meant to have new children. For example, all Controls and Charts extend Region.

Behavioral layout

For these layout managers, you choose the behavior for layouting of your nodes, and they will do the following tasks for you:

  • Calculate child nodes' sizes
  • Initial positioning of the child nodes
  • Reposition nodes if they change their sizes or the layout manager changes its size

The first manager to look at is HBox. It arranges its children in simple rows:

HBox root = new HBox(5);
new Rectangle(50, 50, Color.GREEN),
new Rectangle(75, 75, Color.BLUE),
new Rectangle(90, 90, Color.RED));

The corresponding VBox does the same for columns.

StackPane positions nodes in its center.

As nodes will overlap here, note that you can control their Z-order using the following APIs:

  • Node.toBack() will push it further from the user
  • Note.toFront() will bring it to the top position

Take a look at the following example code:

 Pane root = new StackPane();
Rectangle red;
new Rectangle(50, 50, Color.GREEN), // stays behind blue and red
new Rectangle(75, 75, Color.BLUE),
red = new Rectangle(90, 90, Color.RED));


This is the image that it produces:

Positional layout

This group of managers allows you to choose a more precise location for each component, and they do their best to keep the node there. Each manager provides a distinct way to select where you want to have your component. Let's go through examples and screenshots depicting that.

TilePane and FlowPane

TilePane places nodes in the grid of the same-sized tiles. You can set preferable column and row counts, but TilePane will rearrange them as space allows.

In the following example, you can see different rectangles being located in the same-sized tiles:

Refer to the following code:

// chapter1/layoutmanagers/
public class TilePaneDemo extends Application {

public void start(Stage primaryStage) {
TilePane root = new TilePane(5,5);
// compare to
// FlowPane root = new FlowPane(5, 5);

for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
double size = 5 + 30 * Math.random();
Rectangle rect = new Rectangle(size, size,
(i+j)%2 == 0 ? Color.RED : Color.BLUE);

Scene scene = new Scene(root, 300, 250);

If you don't need tiles to have the same size, you can use FlowPane instead. It tries to squeeze as many elements in the line as their sizes allow. The corresponding code sample differs from the last one only by the layout manager name, and produces the following layout:

BorderPane layout manager

BorderPane suggests several positions to align each subnode: top, bottom, left, right, or center:

Refer to the following code:

BorderPane root = new BorderPane();
root.setRight(new Text("Right "));
root.setCenter(new Text("Center"));
root.setBottom(new Text(" Bottom"));
root.setLeft(new Text(" Left"));

Text top = new Text("Top");

BorderPane.setAlignment(top, Pos.CENTER);

Note the last line, where the static method is used to adjust top-element horizontal alignment. This is a JavaFX-specific approach to set Pane constraints.

AnchorPane layout manager

This manager allows you to anchor any child Node to its sides to keep them in place during resizing:

Refer to the following code:

Rectangle rect = new Rectangle(50, 50, Color.BLUE);

Pane root = new AnchorPane(rect);
AnchorPane.setRightAnchor(rect, 20.);
AnchorPane.setBottomAnchor(rect, 20.);

GridPane layout manager

GridPane is most complex layout manager; it allows users to sets rows and columns where child Nodes can be placed.

You can control a lot of constraints through the API: grow strategy, the relative and absolute sizes of columns and rows, resize policy, and so on. I won't go through all of them to avoid repeating JavaDoc, but will show only a short sample—let's make a small chessboard pattern using GridPane:

GridPane root = new GridPane();
for (int i = 0; i < 5; i++) {
root.getColumnConstraints().add(new ColumnConstraints(50));
root.getRowConstraints().add(new RowConstraints(50));
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
if ((i+j)%2 == 0)
root.add(new Rectangle(30, 30, Color.BLUE), i, j);

We get the following output:


Clock demo

To demonstrate the topics covered in this chapter, I have written a small clock application.

It will become more complex with each upcoming chapter; for the first release it just shows a current local time in text form and updates it every second, demonstrating Stage/Scene usage, one of the layout managers, and the Application FX Thread workflow:

See the inline comments for details about the program:

// chapter1/clock/
public class ClockOne extends Application {
// we are allowed to create UI objects on non-UI thread
private final Text txtTime = new Text();

private volatile boolean enough = false;

// this is timer thread which will update out time view every second
Thread timer = new Thread(() -> {
SimpleDateFormat dt = new SimpleDateFormat("hh:mm:ss");
while(!enough) {
try {
// running "long" operation not on UI thread
} catch (InterruptedException ex) {}
final String time = dt.format(new Date());
Platform.runLater(()-> {
// updating live UI object requires JavaFX App Thread

public void start(Stage stage) {
// Layout Manager
BorderPane root = new BorderPane();

// creating a scene and configuring the stage
Scene scene = new Scene(root, 200, 150);


// stop() method of the Application API
public void stop() {
// we need to stop our working thread after closing a window
// or our program will not exit
enough = true;

public static void main(String[] args) {


In this chapter, we studied the main JavaFX concepts: SceneGraph, Application, Stages, and layout. Also, we provided an overview of the main layout managers and wrote our first few JavaFX programs.

A clock demo was presented to demonstrate a JavaFX application lifecycle and working with the threads.

In the next chapter, we'll look into Scene content: Shapes, Text, and basic controls.

About the Author

  • Sergey Grinev

    Sergey Grinev is an experienced software engineer focused on building reliable, quality processes for Java platforms. He started working in this area during his employment with Oracle, where he was responsible for JavaFX testing. For the last few years, Sergey has worked for Azul Systems, assuring the quality of their custom JVMs.

    Sergey enjoys sharing his experience: he regularly presents Java conferences, gives lessons, and solves questions on Stack Overflow.

    Browse publications by this author

Latest Reviews

(3 reviews total)
Buen libro
The ebook is very good & a great experience
It was very easy to buy the ebook and then download it.

Recommended For You

Mastering JavaFX 10
Unlock this book and the full library for FREE
Start free trial