posts
JavaFX guide:
Go graphical with Java

JavaFX guide: Go graphical with Java

Aug 17, 2022
Dmitry Chuyko
14.5

Although Java doesn’t rule the world of desktop development, it has a powerful solution for developing rich client applications — JavaFX. Introduced in 2008, it currently matures within the OpenJFX project delivering

  • Excellent cross-platform compatibility
  • Modern out-of-the-box solutions for UI
  • Strict update schedule
  • Convenient developer tools

Discover JavaFX — a solution that makes Java an underappreciated rival of .NET and JavaScript when it comes to creating desktop applications!

What is JavaFX?

JavaFX is an open-source platform containing graphics and media tools for developing and deploying rich client applications — programs that store and retrieve data and perform most operations locally, i.e., on a client machine . JavaFX apps run consistently in different environments: desktop, web, mobile, and embedded systems. They can also reference APIs from other Java libraries to use all capabilities of the language and connect to server apps.

JavaFX: Summary of technology

History

Graphical components have been present in Java since the early age of the language. At first, the focus was made on applets, small applications deployed in web browsers. But as the demand for full-blown desktop apps grew, Java evolved accordingly. First Java versions contained only AWT (Abstract Window Toolkit), a low-level abstract graphic API. Swing APIs introduced in 1998 were built on top of AWT and were aimed at extending the AWT functionality.

JavaFX was released as part of the JDK in 2008. The first version of JavaFX was a scripting language built on top of the JVM. Version 2 of JavaFX already came as a set of Java libraries.

Starting with Java 11, JavaFX was separated from JDK and now evolves within the OpenJFX project.

Why JavaFX?

We love Java as a multi-purpose technology suitable for an impressive variety of use cases. But as it focused on conquering the cloud, the domination in desktop development was seized by other technologies. WPF (.NET-based) and JavaScript-based frameworks are currently the most popular tools for developing desktop applications. So why would you use JavaFX instead?

Consider this:

  • JavaFX enables the developers to write clear, manageable code in Java, which is easy to update or debug. Writing code for desktop applications in JavaScript is far more complicated, and cross-platform compatibility of .NET apps is inconsistent
  • Short learning curve for Java developers or programmers who have already worked with Java-like technologies
  • JavaFX includes all necessary libraries for desktop development and supports CSS styling, FXML, and multithreading. It provides many functions out-of-the-box (see the section below), and as a bonus, it has a convenient JavaFX Scene Builder, a visual layout tool for designing UIs without coding
  • JavaFX is open source and part of a strong Java community. Updates with security patches and bug fixes come out regularly, and even when Oracle ceases JavaFX support as part of Java 8 in 2025, the technology will still be developed by the community within the OpenJFX project
  • Thanks to the support for native image technology in Liberica NIK 21.3 and up, the JavaFX app can be bundled and deployed as native executables that take less space on a disk and start up almost instantly

JavaFX features

JavaFX has an extensive range of features for developing GUIs: tables, buttons, trees, menus, and many more. It also supports CSS, 2D and 3D Graphics, and WebView. JavaFX features with examples of subcomponents for better understanding are listed below:

  • Core (FXML, Stage, Scene, etc.)
  • Layout (HBox, VBox, Border Pane, Text Flow, Flow Panel, etc.)
  • UI controls (Label, Button, TextField, MenuBar, etc.)
  • Container controls (Accordion, TablePane, etc.)
  • Web (WebView, etc.)
  • Charts (PieChart, BarChart, etc.)
  • Other concepts (fonts, animation, effects, etc.)

A detailed description of respective components can be found at Javatpoint.

JavaFX resources

Numerous libraries, frameworks, and third-party resources enhance the experience of working with JavaFX. The libraries enable the developers to create beautiful apps with more concise code, and frameworks add extra functionality.

Let’s discuss some of them briefly to illustrate the capabilities of the JavaFX platform you can make use of.

  • MigLayout is an open-source library that aids in developing and managing layouts. It provides tools for multiple layout types: flowing, grip-based, docking, etc. The code written in MigLayout is very concise and represents the appearance of a layout clearly
  • Ikonli is a library providing numerous icon packs for different icons and making it possible to customize and style icons
  • RichTextFX offers tools for creating rich text editors and code editors with syntax highlighting and various fonts
  • JacpFX is a framework that helps to structure the app with loosely coupled, reusable JavaFX components. The task execution can be separated from UI changes in the client application, thus enabling the developers to avoid the multithreading issues. JacpFX functionalities include message-bus communication between components and asynchronous processes support
  • Skija provides Java bindings for Skia, an open-source library for developing rich 2D graphics. It is highly performant, easy to use, and robust, with support for color spaces, modern typography and GPU backends, and highly-optimized GPU rendering

Refer to a GitHub repository by jjenkov with demo JavaFX apps to see various features of this technology in action. Furthermore, the official website of the OpenJFX project provides all essential guides, tutorials, and documentation to master the technology.

Use cases

Although many workloads have been transferred from desktops to the web, desktop applications are not a dying technology. There are numerous cases when local/native applications are a preferred choice for users as they provide a more advanced GUI experience, higher performance, and reliability. Use cases for desktop applications include:

  • IDEs
  • Editors
  • Audio and video editors/players
  • Games

In addition, some web and mobile applications have their desktop counterparts, such as Skype, WhatsApp, Telegram, and Slack. So desktop development is still a lucrative field for developers, which makes JavaFX a technology worth learning.

Furthermore, JavaFX goes beyond pure desktop development. For instance, JavaFX apps can be built as native images and used on mobile devices: Gluon offers tools for that purpose, and Liberica Native Image Kit can be used for the fast and convenient transformation of Java apps into native executables.

JavaFX also goes well with embedded devices such as Raspberry Pi. Refer to our guide on running Liberica JDK with JavaFX on this popular single-board computer.

Support roadmap

Oracle Java 8 still includes JavaFX, which will be supported until March 2025. The release schedule of OpenJFX is based on quarterly updates with security patches and bug fixes. The community provides LTS and minor versions and commercial support by Gluon upon request. BellSoft bundles JavaFX with its own OpenJDK distribution, Liberica JDK (see below).

JavaFX roadmap
ReleaseGA dateLatest versionLong-term support
Java 11September 201811.0.16 (July 2022)Yes
Java 17September 202117.0.4 (July 2022)Yes
Java 18 (current)March 202218.0.2 (July 2022)No
Java 19September 2022 (planned)Early accessNo
JavaFX support roadmap

JavaFX comes as a platform-specific SDK, jmods, or a set of artifacts. If you want to use the software with your Java runtime, download the necessary bundle from the developer’s website. We deliver a special flavor of Liberica JDK (Full version) containing LibericaFX — our instance of OpenJFX. Liberica for Embedded also comes with LibericaFX enabling the developers to create GUIs for embedded systems.

JavaFX integrated into the runtime is very convenient:

  • Minimize time and effort spent on installing JavaFX as a separate plugin
  • Get timely fixes together with runtime updates
  • Receive first-hand support from our engineers within the scope of JDK support

JavaFX vs Swing

You might be wondering at that point, “If a JDK already contains Swing, why should I bother with JavaFX?”

As mentioned, JavaFX was designed as a substitution for Swing, which lacks many modern features. As a result, it offers many more opportunities for desktop development than Swing. Here is a short comparison of both technologies:

JavaFXSwing
Used for developing rich client applications with moden user interfaceLegacy library for GUI development
Cleaner code baseMany legacy features
Integrated support for MVCInconsistent support for MVC
Evolves within the community that regularly introduces enhancements and new featuresNo new functions are added
Supports both CSS and code-based stylingOnly code-based styling
Integrated API for concurrencyNo built-in API for concurrency
FXML for declarative layoutNo support for declarative layout
Built-in 3D graphics supportRequires additional API for 3D
Support for property bindingNo property binding
Comes as a separate bundle starting with JDK 11Included into JDK by default
Comparative table for Swing and JavaFX

Let’s compare two demo apps written with JavaFX and Swing, which illustrate button customization:

import javafx.application.Application;

import javafx.scene.Scene;

import javafx.scene.control.Button;

import javafx.scene.layout.VBox;

import javafx.scene.transform.Scale;

import javafx.stage.Stage;

public class ScaleTransformationDemo extends Application {

   public static void main(String[] args) {

       launch(args);

   }

   @Override

   public void start(Stage primaryStage) throws Exception {

       Button button = new Button();

       button.setText("Click me!");

       Scale scaleTransformation = new Scale();

       scaleTransformation.setX(3.0);

       scaleTransformation.setY(2.0);

       scaleTransformation.setPivotX(0);

       scaleTransformation.setPivotY(0);

       button.getTransforms().add(scaleTransformation);

       VBox vbox = new VBox(button);

       Scene scene = new Scene(vbox);

       primaryStage.setScene(scene);

       primaryStage.setWidth(512);

       primaryStage.setHeight(256);

       primaryStage.show();

   }

}

In the example above taken from the JavaFX Button tutorial, we added a scale transformation. The customization process with Swing is different:

import javax.swing.*;

import javax.swing.border.EmptyBorder;

import javax.swing.plaf.basic.BasicButtonUI;

import java.awt.*;

public class ButtonCustomization extends BasicButtonUI {

   public static void main(String[] args) {

       JFrame f = new JFrame("Button UI Test");

       f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

       JPanel p = new JPanel();

       p.setBackground(Color.white);

       f.setContentPane(p);

       p.setLayout(new FlowLayout(5, 5, 5));

       p.setBorder(new EmptyBorder(10, 10, 10, 10));

       final JButton button = new JButton("Click me!");

       button.setFont(new Font("Calibri", Font.PLAIN, 14));

       button.setBackground(new Color(0x2dce98));

       button.setForeground(Color.white);

       button.setUI(new ButtonCustomization());

       p.add(button);

       f.pack();

       f.setLocation(500, 500);

       f.setVisible(true);

   }

   @Override

   public void installUI(JComponent c) {

       super.installUI(c);

       AbstractButton button = (AbstractButton) c;

       button.setOpaque(false);

       button.setBorder(new EmptyBorder(5, 15, 5, 15));

   }

   @Override

   public void paint(Graphics g, JComponent c) {

       AbstractButton b = (AbstractButton) c;

       paintBackground(g, b, b.getModel().isPressed() ? 2 : 0);

       super.paint(g, c);

   }

   private void paintBackground(Graphics g, JComponent c, int yOffset) {

       Dimension size = c.getSize();

       Graphics2D g2 = (Graphics2D) g;

       g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

       g.setColor(c.getBackground().darker());

       g.fillRoundRect(0, yOffset, size.width, size.height - yOffset, 10, 10);

       g.setColor(c.getBackground());

       g.fillRoundRect(0, yOffset, size.width, size.height + yOffset - 5, 10, 10);

   }

}

To avoid the complexity of code-based styling with Swing, try using CSS supported by JavaFX. Refer to the official JavaFX CSS Reference Guide for details.

Now, if you want to animate the scaling of the JavaFX button, you simply need to use ScaleTransition. The same task won’t be as easy for Swing because it neither has a dedicated class nor concurrency support.

Conclusion

To sum up, Java once again proves its might with JavaFX. Although companies already working with .NET or JavaScript are unlikely to migrate to other technologies, if you use Java in enterprise development or are thinking about broadening your skillset, JavaFX might be right up your alley! And native images bring even more power to JavaFX applications, so check out the tutorial on turning JavaFX apps into native executables!

 

Subcribe to our newsletter

figure

Read the industry news, receive solutions to your problems, and find the ways to save money.

Further reading