JavaFX Essentials

4.3 (7 reviews total)
By Mohamed Taman
    What do you get with a Packt Subscription?

  • Instant access to this title and 7,500+ eBooks & Videos
  • Constantly updated with 100+ new titles each month
  • Breadth and depth in over 1,000+ technologies
  1. Free Chapter
    Getting Started with JavaFX 8

About this book

JavaFX is a software platform to create and deliver rich Internet applications (RIAs) that can run across a wide variety of devices.

JavaFX Essentials will help you to design and build high performance JavaFX 8-based applications that run on a variety of devices.

Starting with the basics of the framework, it will take you all the way through creating your first working application to discovering the core and main JavaFX 8 features, then controlling and monitoring your outside world. The examples provided illustrate different JavaFX and Java SE 8 features.

This guide is an invaluable tutorial if you are planning to develop and create JavaFX 8 applications to run on a variety of devices and platforms.

Publication date:
June 2015


Chapter 1. Getting Started with JavaFX 8

JavaFX is Java's next-generation Graphical User Interface (GUI) toolkit. It's a platform that makes it easy to rapidly build high-performance Java client-side applications.

JavaFX's underlying engines take advantage of modern GPUs through hardware-accelerated graphics, while providing well-designed programming interfaces, thus enabling developers to combine graphics, animation, and UI controls.

These capabilities allow you to deliver a compelling, complex, and fully customizable client GUI for your customer that will make them quite impressed.

While the original targets of Java were the embedded and client worlds, since 2006, many reasons pushed the Java language to become the top development platform for the Enterprise world.

But recently, with the JavaFX platform's entrance as the standard client GUI, those original targets have started to gain popularity again.

Although it is much more than just a GUI toolkit, JavaFX allows Java developers to create client applications with compelling user interfaces that easily connect to backend systems.

In addition, JavaFX's flexible FXML support allows you to build MVC (Model-View-Controller) architectural pattern applications easily, and use the WYSIWYG approach using the Scene Builder tool.

JavaFX's bindings feature simplified communication between entities and support MVC even further. In addition to that, JavaFX provides fast, customizable UI modeling using CSS.

By adding a full-fledged WebView component with a document model, mapping to Java code is easy and provides great support for 3D and media capabilities.

In this chapter, we are going to cover the following topics:

  • What is JavaFX and what are its targeted platforms?

  • A walk through JavaFX history

  • JavaFX goals, features, and what's new in JavaFX 8

  • How to install Java SE 8, JavaFX 8, NetBeans, and configuring environment variables

  • Developing a "Hello World" JavaFX 8 application, and understanding the JavaFX 8 basic application architecture and building blocks


JavaFX goals

JavaFX came to light with a primary goal – to be used across many types of devices, such as embedded devices, smartphones, TVs, tablet computers, and desktops. JavaFX also follows Java's write once, run anywhere paradigm.

JavaFX 8 is written totally from scratch in Java language, it makes you feel at home. Therefore, applications written in JavaFX can be deployed on desktops, laptops, the Web, embedded systems, mobiles, and tablets.

Embedded systems are no longer supported by Oracle; it is left to companies like ARM and others to support it. Mobile devices have never been supported from JavaFX 2.x to 8.x; the support exists now only because of OpenJFX. The community has benefitted from open source bringing JavaFX to mobile environments.

For more about OpenJFX, visit

JavaFX is a set of graphics and a media package that enables developers to design, create, test, debug, and deploy rich client applications that operate consistently across diverse platforms, in one bundle, without the need for many separate libraries, frameworks, and APIs to achieve the same goal. These separate libraries include media, UI controls, WebView, 3D, and 2D APIs.

So if you are a Java frontend developer, an experienced Java Swing, Flash/Flex, SWT, or web developer looking to take your client-side applications to the next level, and you want to develop an attractive and complex user interface for your customer, then you are on track learning JavaFX skills – this book is for you.


Getting started

This chapter is an introduction to JavaFX 8; we have already talked about JavaFX 8 as a technology and why you should care about it.

Next, we will navigate its history, exploring its core features and where it could be used.

Before you start using this book to learn JavaFX 8, we will go through the preparation of your development environment by installing various required software bundles, to be able to compile and run many of its examples.

In this chapter, you will learn how to install the required software, such as the Java Development Kit JDK and the NetBeans Integrated Development Environment (IDE).

After installing the required software, you will begin by creating a traditional Hello JavaFX 8 example. Once you feel comfortable with the development environment, as a final verification that we are on the right track, we will walk through the Hello JavaFX 8 source code to understand the basic JavaFX 8 application architecture.


If you are already familiar with the installation of the JDK and the NetBeans IDE, you can skip to Chapter 2, JavaFX 8 Essentials and Creating a custom UI, which covers JavaFX 8 fundamentals and how to create a custom UI component.

So what you are waiting for? Let's get started!


JavaFX history

You might believe JavaFX is quite a new technology, but it actually isn't. JavaFX has been here for a long time; unofficially since 2005. Ever since Sun Microsystems acquired the company SeeBeyond, there has been a graphics-rich scripting language known as F3 (Form Follows Function), which was created by engineer Chris Oliver.

At the JavaOne 2007 conference, Sun Microsystems officially unveiled JavaFX as the language's name instead of F3. During the period 2007 to 2010, Oracle acquired many big companies like BEA Systems, JD Edwards, Siebel Systems, and so on. I was working for Oracle with the responsibility of integrating different customer support channels to the Oracle support website MetaLink, as it was called at that time.

On April 20, 2009, Oracle Corporation announced the acquisition of Sun Microsystems, making Oracle the new steward of JavaFX.

At JavaOne 2010, Oracle announced the JavaFX roadmap, which included its plans to phase out the JavaFX 1.3 scripting language and recreate the JavaFX platform for the Java platform as Java-based APIs. As promised, JavaFX 2.0 SDK was released at JavaOne in October 2011.

In addition to the release of JavaFX 2.0, Oracle took the platform to the next level by announcing its commitment to take steps to make JavaFX open source, thus allowing Java's versatile and strong community to help move the platform forward. Making JavaFX open source increased its adoption, enabled a quicker turnaround time on bug fixes, and generated new enhancements.

Between the versions JavaFX 2.1 and 2.2, the number of new features grew rapidly. JavaFX 2.1 was the official release of the Java SDK on Mac OS. JavaFX 2.2 was the official release of the Java SDK on the Linux operating system.

There was no such thing as JavaFX 3.x, but the big change in the Java development world happened with the Java SE 8 release, which was announced on March 18, 2014. Java SE 8 has many new APIs and language enhancements, which include Lambdas, Stream API, Nashorn JavaScript engine, and JavaFX APIs, which are being incorporated into standard JDK bundles, and JavaFX version becomes 8 as direct successor to JavaFX 2.0.

To see all of the new features in Java SE 8, visit

When is JavaFX 8 available?

The answer is now. As mentioned before, Java SE 8 was released on March 18, 2014. For developers who use Java to build client-site applications, the JavaFX rich Internet application framework supports Java 8 now.

Most of the Java enterprise edition vendors support Java 8 too. Whether you move to Java SE 8 right away depends on the kind of projects you're working on.


In fact, as outlined in the Oracle JDK Support Roadmap, after April 2015, Oracle will not post further updates of Java SE 7 to its public download sites.

The JavaFX APIs are available as a fully integrated feature of the Java SE Runtime Environment (JRE) and JDK. The JDK is available for all major desktop platforms (Windows, Mac OS X, Solaris, and Linux), therefore JavaFX will also run on all major desktop platforms.

Relating to JavaFX 8, it supports the following APIs:

  • 3D graphics

  • Rich text support

  • Printing APIs.


JavaFX features

The following features are included in JavaFX 8 and later releases as per JavaFX's official documentation:

  • Java APIs: JavaFX is a Java library that consists of classes and interfaces that are written in Java code.

  • FXML and Scene Builder: This is an XML-based declarative markup language for constructing a JavaFX application user interface. You can code in FXML or use JavaFX Scene Builder to interactively design the GUI. Scene Builder generates FXML markup that can be ported to an IDE like NetBeans, where you can add the business logic. Moreover, the FXML file that is generated can be used directly inside the JavaFX application.

  • WebView: This is a web component that uses WebKit, an HTML render engine technology, to make it possible to embed web pages within a JavaFX application. JavaScript running in WebView can call Java APIs and vice-versa.

  • Swing/SWT interoperability: The existing Swing and SWT applications can benefit from JavaFX features such as rich graphics, media playback, and embedded web content.

  • Built-in UI controls and CSS: JavaFX provides all the major UI controls, and some extra uncommon controls like charts, pagination, and accordion that are required to develop a full-featured application. Components can be skinned with standard web technologies such as CSS.

  • 3D graphics features: Support for the 3D graphics library is included.

  • Canvas API: You can draw directly inside a JavaFX scene area using the Canvas API, which consists of one graphical element (node).

  • Multitouch support: Multitouch operations are supported based on the capabilities of the underlying platform.

  • Hardware-accelerated graphics pipeline: JavaFX graphics are based on the graphics-rendering pipeline, Prism. The Prism engine smoothly and quickly renders JavaFX graphics when used with a supported graphics card or graphics processing unit (GPU). If a system does not feature one of them, then Prism defaults to the software-rendering stack.

  • High-performance media engine: This engine provides a stable, low-latency media framework that is based on the GStreamer multimedia framework. The playback of web multimedia content is supported with the media pipeline.

  • Self-contained deployment model: Self-contained application packages have all of the application resources and a private copy of the Java and JavaFX runtimes. They are distributed as native installable packages and provide the same installation and launch experience as native applications for that operating system.

What's new in JavaFX 8

The following is a brief summary of the new features and significant product changes made in the JavaFX component of the Java SE 8 release:

  • The new Modena theme is now the default theme for JavaFX applications.

  • Support for additional HTML5 features, including Web Sockets, Web Workers, Web Fonts, and printing capabilities have been added.

  • The API enables you to embed Swing content into JavaFX applications with the new SwingNode class, which improves the Swing interoperability feature.

  • DatePicker, Spinner, and TableView built-in UI controls are now available.

  • It provides the public JavaFX printing APIs through the javafx.print package.

  • Support for Hi-DPI displays has been made available.

  • CSS-styleable classes became public APIs.

  • A scheduled service class has been introduced.

  • The 3D graphics library has been enhanced with several new API classes.

  • Major updates have been added to the Camera API class in this release.

  • Now JavaFX 8 supports rich text capabilities. These include bidirectional and complex text scripts such as Thai and Hindi in UI controls, and multiline, multistyle text in text nodes.

  • Dialogs and accessibility APIs are supported.

In Appendix, Become a JavaFX Guru, I have provided a list of all the references (links, books, magazines, articles, blogs, and tools) and real JavaFX 8 production applications you will need to become a JavaFX guru.

The following figure shows the Ensemble8.jar application built using JavaFX 8, showing examples dealing with various JavaFX 8 components, topics and concepts. More interestingly, the source code is available to learn from and modify – consult the last chapter to see how to install this application.

JavaFX 8 applications

There are many topics covered by the application, especially the new JavaFX 8 3D APIs, which can be found under the Graphics 3D section as seen in the following figure:

JavaFX 8 3D applications


Installing the required software

So far, we have had a good introduction to JavaFX and I am as eager as you to start creating and launching our first "Hello JavaFX 8" application. But this can't happen without downloading and installing the right tools that will allow us to create and compile most of the book's code.

You'll need to download and install Java 8 Java Development Kit (JDK) or a later version. Not the runtime version (JRE).

Download the latest Java SE 8u45 JDK or higher from the following location:

Download and install NetBeans 8.0.2 or higher from the following link, though the NetBeans IDE All Bundle is recommended, you can use the Java EE bundle as well, as shown in the figure:

NetBeans bundles download.

Currently, JavaFX 8 runs on the following operating systems:

  • Windows OS (XP, Vista, 7, 8) 32- and 64-bit

  • Mac OS X (64-bit)

  • Linux (32- and 64-bit), Linux ARMv6/7 VFP, HardFP ABI (32-bit)

  • Solaris (32- and 64-bit)

Installing Java SE 8 JDK

The steps outlined in this section will guide you to successfully download and install Java SE 8. Download the Java SE 8 JDK from the following location:

In the following steps, the Java SE 8u45 JDK 64-bit version (at the time of writing) on the Mac OS X Yosemite (10.10.3) operating system will be used as an example.

The steps are similar on other operating systems and JDK versions. However, if your environment is different, refer to the following link for additional details:

The following are steps to install the Java SE 8 JDK:

  1. Install the Java 8 JDK by launching the image file jdk-8u45-macosx-x64.dmg. A screen will appear that looks like the following screenshot once you've launched the JDK 8 setup image file. That's the package setup file. Double-click on it and the installer will launch:

    JDK 8 setup image file


    Typically, you will need administrator rights on the machine to install the software.

  2. Begin the setup of the Java 8 JDK. The screen in the following screenshot will appear at the beginning of the installation process. Click on the Continue button, next on the Installation type screen wizard, click on Install to begin the installation.

    Java SE Development Kit 8 setup

  3. Once you hit Install, you may be asked to supply your password. Supply it, click on Ok and the installation will proceed with a progress bar, as shown in following figure:

    Java SE Development Kit 8 installation in progress

  4. The setup will complete the installation of the Java 8 SE Development Kit. click on the Close button to exit.

Setting environment variables

Now you need to set a couple of key environment variables. How you set them and the values they should be set to vary depending on your operating system. The two variables to be set are:

  • JAVA_HOME: This tells your operating system where the Java installation directory is.

  • PATH: This specifies where the Java executable directory resides. This environment variable lets the system search paths or directories containing executable files. The Java executables reside in the bin directory under the JAVA_HOME home directory.

To make JAVA_HOME and PATH more permanent, you will want to add them to your system in such a way that they are always made available whenever you boot or log in. Depending on your operating system, you will need to be able to edit environment variable names and values.

In the Windows environment, you can use the keyboard shortcut Windows logo key + Pause/Break key and then click on Advanced system settings to display the Systems Property dialog.

Next, click on Environment Variables. This is where you can add, edit, and delete environment variables. You will add or edit the JAVA_HOME environment variable by using the installed home directory as the value. Shown in this screenshot is the Environment Variables dialog on the Windows operating system:

Windows Environment Variables

Let's set the environment variables:

  • To set your JAVA_HOME environment variable for the Mac OS X platform, you will need to launch a terminal window to edit your home directory's .bash_profile file by adding the following export command:

    export JAVA_HOME=$(/usr/libexec/java_home -v 1.8)
  • On Linux and other Unix operating systems that use Bash shell environments, launch a terminal window and edit either the ~/.bashrc or ~/.profile file to contain the export commands:

    export JAVA_HOME=/usr/java/jdk1.8.0
    export PATH=$PATH:$JAVA_HOME/bin
  • On Linux and other Unix operating systems that use C shell (csh) environments, launch a terminal window and edit either the ~/.cshrc or ~/.login file to contain the setenv commands:

    setenv JAVA_HOME /usr/java/jdk1.8.0_45
    setenv PATH ${JAVA_HOME}/bin:${PATH}

Once you've set up your path and the JAVA_HOME environment variables, you will want to verify your setup by launching a terminal window and executing the following two commands from the command prompt:

java -version
javac –version


The output in each case should display a message indicating the Java SE 8 version of the language and runtime.

Installing the NetBeans IDE

When developing JavaFX applications, you will be using the NetBeans IDE (or any other IDE of your preference). Be sure to download the correct NetBeans version containing JavaFX. To install the NetBeans IDE, follow these steps:

  1. Download the NetBeans IDE 8.0.2 or later from the following location:

  2. Launch the .dmg image file netbeans-8.0.2-macosx.dmg. The image will be verified and a folder containing the installer package archive, netbeans-8.0.2.pkg, will open; double-click on it to launch the installer. A dialog box will appear with the message: This package will run a program to determine if the software can be installed. Click on the Continue button.

  3. Once you've launched the NetBeans installation dialog, click on continue again. Next, accept the license and click on Continue and then on Agree.

  4. Click on the Install button to proceed. The following screenshot shows a Mac security warning prompt; supply your password and click on Install Software.

    The Mac Security Warning dialog

  5. The NetBeans IDE installation processes will begin. The following screenshot shows the installation progress bar:

    Installation progress

  6. Click on the Close button to complete the installation, as shown here:

    Setup complete

Now you are ready to move on and create JavaFX applications.


Creating "Hello World" JavaFX-style applications

The best way to show you what it is like to create and build a JavaFX application would be with a Hello World application.

In this section, you will be using the NetBeans IDE we just installed to develop, compile, and run a JavaFX-based Hello World application.

Using the Netbeans IDE

To quickly get started with creating, coding, compiling, and running a simple JavaFX-style Hello World application using the NetBeans IDE, follow the steps outlined in this section:

  1. From the File menu, choose New Project.

  2. From JavaFX application category, choose JavaFX Application. Click on Next.

  3. Name the project HelloJavaFX. Optionally, you can define the package structure for application classes. Then click on Finish as shown in the following screenshot:

    New JavaFX application wizard

    NetBeans opens the file and populates it with the code for a basic "Hello World" application.


    You will find that this version of code has been modified a bit from the one NetBeans actually creates, and you can compare them to find differences, but they have the same structure. I did that to show the result on the text node on the Scene instead of the console when clicking on the Say 'Hello World' button. For that, a VBox container has also been used.

  4. Right-click on the project and click on Run from the menu as shown here:

    Running the application

  5. NetBeans will compile and run the application. The output should be as shown in the following screenshot:

    JavaFX Hello World launched from the NetBeans IDE

  6. Click on the button and you should see the following result:

    JavaFX Hello World results

Here is the modified code of the basic Hello world application (

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.text.Text;
import javafx.stage.Stage;
import static javafx.geometry.Pos.CENTER;
import javafx.scene.layout.VBox;

  * @author mohamed_taman
public class HelloJavaFX extends Application {
  public void start(Stage primaryStage) {
    Button btn = new Button();
    Text message = new Text();
    btn.setText("Say 'Hello World'");
    btn.setOnAction(event -> {
      message.setText("Hello World! JavaFX style :)");
    VBox root = new VBox(10,btn,message);
    Scene scene = new Scene(root, 300, 250);
    primaryStage.setTitle("Hello JavaFX 8 World!");
  public static void main(String[] args) {

How it works

Here are the important things to know about the basic structure of a JavaFX application:

  • The main class for a JavaFX application should extend the javafx.application.Application class. The start() method is the main entry point for all JavaFX applications.

  • A JavaFX application defines the user interface container by means of a stage and a scene. The JavaFX Stage class is the top-level JavaFX container. The JavaFX Scene class is the container for all content. The following code snippet creates a stage and scene and makes the scene visible in a given pixel size – new Scene(root, 300, 250).

  • In JavaFX, the content of the scene is represented as a hierarchical scene graph of nodes. In this example, the root node is a VBox layout object, which is a resizable layout node. This means that the root node's size tracks the scene's size and changes when a user resizes the stage.

  • The VBox is used here as the container that arranges its content nodes vertically in a single column with multiple rows. We have added the button btn control to the first row in the column, then the text message control to the second row on the same column, with vertical space of 10 pixels, as in the following code snippet:

    VBox root = new VBox(10,btn,message);
  • We set the button control with text, plus an event handler to set the message text control to Hello World! JavaFX style :) when the button is clicked on.

  • You might note a strange code syntax written in Java, with no compiler errors. This is a Lambda expression, which has been added to Java SE 8, and we are going to talk about it briefly in Chapter 2, JavaFX 8 Essentials and Creating a custom UI. With a slight comparison to old anonymous inner classes style, it is cleaner and more concise to use Lambda expression now. Have a look at this comparison of code:

    Old School:

    btn.setOnAction(new EventHandler<ActionEvent>() {
      public void handle(ActionEvent event) {
        message.setText("Hello World! JavaFX style :)");

    New Era:

    btn.setOnAction(event -> {
        message.setText("Hello World! JavaFX style :)");
  • The main() method is not required for JavaFX applications when the JAR file for the application is created with the JavaFX Packager tool, which embeds the JavaFX Launcher in the JAR file.

  • However, it is useful to include the main() method so you can run JAR files that were created without the JavaFX Launcher, such as when using an IDE in which the JavaFX tools are not fully integrated. Also, Swing applications that embed JavaFX code require the main() method.

  • Here, in our main() method's entry point, we launch the JavaFX application by simply passing in the command-line arguments to the Application.launch() method.

  • After the Application.launch() method has executed, the application will enter a ready state and the framework internals will invoke the start() method to begin.

  • At this point, the program execution occurs on the JavaFX application thread and not on the main thread. When the start() method is invoked, a JavaFX javafx.stage.Stage object is available for you to use and manipulate.


Advanced topics will be discussed at length in the next chapters. More importantly, we will go through the JavaFX application thread in the coming chapters. In the last three chapters, we will see how to bring the result from other threads into the JavaFX application thread in order to render it correctly on the scene.



So far, you have learned what JavaFX is and seen its power. You have managed to download and install both Java 8 JDK and NetBeans IDE. After successfully installing the prerequisite software, you created a JavaFX Hello World GUI application through the NetBeans IDE. After learning how to compile and run a JavaFX application, you did a quick code walkthrough of the source file

Next, in Chapter 2, JavaFX 8 Essentials and Creating a custom you'll learn about JavaFX 8 architecture components and engines, which allow JavaFX applications to run efficiently and smoothly under the hood. You will also learn about the most common layout UI components and get an idea about theming your application as a whole or as individual scene nodes.

We will also be covering Java SE 8's most important feature, Lambda expressions, and how it works. We will then get insights into Scene Builder as a declarative UI and productive tool, then learn about generated FXML-based markup document and how to import it into NetBeans IDE to continue your application logic implementation to associate it to the already declared UI controls inside your FXML document.

Finally, you will be able to create a custom UI component that isn't bundled with default JavaFX 8 UI controls.

About the Author

  • Mohamed Taman

    Mohamed Taman is an Enterprise Architect/Senior Software Engineer at WebCentric Company. He is a frequent consultant with around 20+ years' experience in Java. He holds a Diploma in Computer and Automatic Control in 1999, and a BSc in computer systems engineering, with a major in Electrical Engineering in 2005. He formerly lived in Cairo, Egypt, but has just relocated to Belgrade, Serbia.

    Mohamed's experiences strongly include development in Java and JavaScript, web, mobile, and IoT for industries including financial, banking, tourism, government, and healthcare; he has worked for Pfizer, Silicon Expert, Google, Oracle, and e-finance. He has worked with a number of technologies including UX, user-facing GUI frontend engineering, DevOps, cloud computing, AI, ML, big data, Blockchain, backend, mid-tiers, and integrations of large-scale systems in Agile environments.

    Mohamed enjoys talking at international conferences to evangelize Java standards, Java EE, Java SE, and his experience in different domains, as he is a very knowledgeable Java community member. He worked closely with the teams responsible for the development of the JDK and Java EE.

    In addition, he is a member of Adopt-a-JSR of Java EE 8, OpenJDK 9, 10, and 11, and JavaFX programs. He is a JCP member, was 2014 JCP Executive Committee member, and is on the Java Community Process (JCP) expert group (EG) for JSRs 354, 363, and 373.

    Community-wise, Mohamed is a Java Champion, Oracle Developer Champion, EGJUG leader, MoroccoJUG member, and Oracle Egypt Architects Club board member, and won the 2014 and 2015 Duke's choice awards, 11th annual JCP adopt 2013 awards, and United Nations Mobile Hackathon 2015, gaining second place worldwide.

    Mohamed is the author of his own blog, a Most Valuable Blogger (MVB) at DZone, and a Java Code Geek. Mohamed authored the JavaFX Essentials book for Packt Publishing and was a reviewer of Getting Started with Oracle Public Cloud for Packt Publishing.

    You can find him on the following channels:

    Twitter: @_tamanm





    e-mail: [email protected]

    Browse publications by this author

Latest Reviews

(7 reviews total)
Very interesting content of the book.
Apenas estoy leyéndolo, todavía no puedo opinar
Book has been a mixed bag. Good enough until you get into the details, then sample code either isn't complete or doesn't run. But it gets me moving in the right direction...
JavaFX Essentials
Unlock this book and the full library FREE for 7 days
Start now