JavaData & JavaWhat is JavaFX? An Introduction

What is JavaFX? An Introduction

Developer.com content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More.

JavaFX is a library that enables you to create and deploy a rich client application. The library is shipped along with the Java SDK by default (no separate installation required). The main purpose of this library is to enable a developer to create a consistent look and feel across a variety of platforms such as cell phone, browser, car dashboard, and so forth. In a way, almost any imaginable devices that require Java GUI support can benefit. The article shall show you what JavaFX is rather than provide a dry conceptual overview. Also. we’ll cover tersely a few of its key capabilities with implementation rather than being extensive.

JavaFX and Swing

Swing has been around for quite some time with the same purpose of providing UI needs of Java. In comparison with JavaFX, Swing is a complex collection of UI components that keeps on adding a few more bugs every time new features are included into an already unmanageable design. However, Swing undoubtedly offers superb flexibility and capability in creating a graphical user interface. Having a consistent look and feel across multiple platforms requires a lean construct with simple and elegant design. Also, there are issues of threading, collection, and event queue management. Swing classes are not built to leverage graphical hardware components. This reduces performance and lacks efficiency when dealing with complex graphics. To mitigate all these deficiencies, Swing must be thoroughly revamped and redesigned from scratch. JavaFX, in fact, did that and brought a fresh new UI framework into the family, first as an interpreted JavaFX script language, then as a full-blown UI library. Although JavaFX is still growing, it’s just a matter of time before JavaFX becomes the de-facto UI standard of Java, toppling Swing.

Architecture

JavaFX is by far better than Swing at handling graphics because it uses a hardware-accelerated graphics pipeline called Prism to do the rendering job. Rendering is processor intensive and best handled natively with GPU support, although software rendering is also possible. Prism leverages either a hardware or software rendering mechanism and, behind the scenes, uses DirectX or OpenGL to fully accelerate graphic usage. However, on encountering an incompatible underlying piece of hardware, it falls back to Java2D for rendering. As should be obvious, hardware rendering is best whereas Java2D is a supplementary Hobson’s choice.

FX1
Figure 1: The JavaFX architecture

JavaFX uses a window toolkit called Glass that leverages the native platform for windowing. Also, it has its own resources to fall back on if native windowing fails. Unlike AWT, which manages its own event, the Glass window toolkit uses the native platform’s event queue mechanism to schedule thread usage. It acts as a coordinator and handles event-thread activities using Pulse. Pulse events are events that are queued to be popped at the appropriate time by the JavaFX application thread when fired from a scene graph elements. The event state is rippled down through the rendering layer without direct intervention. If no pulse occurs, it still is throttled at the rate of 60 fps. This makes it possible to handle events asynchronously.

However, neither Glass not Prism is directly accessible through Java code; instead, they are interfaced through Quantum toolkit. The Quantum toolkit also provides an interface for media and a Web engine along with Prism and Glass. As a result, The JavaFX components have a consistent look and feel be it a desktop application or a Web application, and can leverage the module according to the requirement without worrying about inconsistency. Generally, the use of Quantum toolkit begins with the Scene graph.

Layout and UI Controls

Layouts are particularly useful to have consistent arrangements of a UI control such as Buttons, Texts, Shapes, and so on within the viewable area, even on resize. JavaFX layouts are simpler and more intuitive to implement that Swing layouts. Some common layouts are:

  • javax.scene.layout.Hbox: Lays out UI controls within a horizontal box
  • javax.scene.layout.Vbox: Lays out UI controls within a vertical box
  • javax.scene.layout.FlowPane: UI controls are arranged in a flow that wraps at the flow pane interior
  • javax.scene.layout.BorderPane: UI controls are laid out in the left, top, right, bottom, and centre position of the scene
  • javax.scene.layout.GridPane: Lays out UI controls in a tabular fashion, in grids of rows and columns

A Quick Example

package simplejavafxapp;

import javafx.application.Application;
import javafx.geometry.HPos;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.*;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.scene.text.Text;
import javafx.stage.Stage;

public class SimpleJavaFXApp extends Application {

   @Override
   public void start(Stage stage) {
      stage.setTitle("Login");
      BorderPane root = new BorderPane();
      Scene scene = new Scene(root, 380, 150, Color.WHITE);

      GridPane gridpane = new GridPane();
      gridpane.setPadding(new Insets(5));
      gridpane.setHgap(5);
      gridpane.setVgap(5);

      ColumnConstraints col1 = new ColumnConstraints(100);
      ColumnConstraints col2 = new ColumnConstraints(50, 150, 300);
      col2.setHgrow(Priority.ALWAYS);
      gridpane.getColumnConstraints().addAll(col1, col2);

      Label userNameLabel = new Label("User Name");
      TextField userNameField = new TextField();
      Label passwordLabel = new Label("Password");
      PasswordField passwordField = new PasswordField();

      Button loginButton = new Button("Login");

      GridPane.setHalignment(userNameLabel, HPos.RIGHT);
      gridpane.add(userNameLabel, 0, 0);

      GridPane.setHalignment(passwordLabel, HPos.RIGHT);
      gridpane.add(passwordLabel, 0, 1);

      GridPane.setHalignment(userNameField, HPos.LEFT);
      gridpane.add(userNameField, 1, 0);

      GridPane.setHalignment(passwordField, HPos.LEFT);
      gridpane.add(passwordField, 1, 1);

      GridPane.setHalignment(loginButton, HPos.RIGHT);
      gridpane.add(loginButton, 1, 2);
      FlowPane topBanner = new FlowPane();
      topBanner.setPrefHeight(40);
      String bgStyle = "-fx-background-color: lightblue;"
         + "-fx-background-inset: 5px;";

      Text contactText = new Text(" Credentials");
      contactText.setFill(Color.WHITE);

      Font serif = Font.font("Dialog", 30);
      contactText.setFont(serif);
      topBanner.getChildren().add(contactText);

      root.setTop(topBanner);
      root.setCenter(gridpane);

      stage.setScene(scene);
      stage.show();
   }
   public static void main(String[] args) {
       launch(args);
   }
}

FX2
Figure 2: The Credentials window

Graphics and Animation

In general, the tools used for graphics and animation programming are different from application programming because application developers are more concerned about business logic than looks. Intriguingly, JavaFX provides tools that unite both of those ends commendably. With a rich set of graphics and animation APIs, a developer can leverage an extra edge of look and feel in the application. This is particularly useful in creating a graphical view of some statistical data. Refer to these articles, “Using Graphics in JavaFX” and “Doing Animation in JavaFX,” for more information specific to this concept.

A Quick Example

package simplejavafxapp;

import java.util.Random;
import javafx.application.Application;
import javafx.scene.*;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;

public class SimpleJavaFXApp extends Application {

   @Override
   public void start(Stage stage) {
      stage.setTitle("Drawing Text");
      Group root = new Group();
      Scene scene = new Scene(root, 600, 600, Color.WHITE);
      Random random = new Random(System.currentTimeMillis());

      double r = 0.0;

      for (int i = 0; i < 200; i++, r += 1) {

         Rectangle rec = new Rectangle(scene.getWidth() /
            2 - 200, scene.getHeight() / 2, 400, 2);

         rec.setFill(Color.rgb(random.nextInt(255),
            random.nextInt(255), random.nextInt(255),
            random.nextDouble()));
         rec.setRotate(r);

         root.getChildren().add(rec);
      }

      stage.setScene(scene);
      stage.show();
   }

   public static void main(String[] args) {
      launch(args);
   }
}

FX3
Figure 3: A graphics demonstration

JavaFX Media

The JavaFX media API enables a developer to incorporate audio and video capabilities into a Java application. The Media API is designed to be cross platform; that means multimedia content can be implemented in an equivalent manner while coding across multiple devices (tablet, media player, TV, and the like). The MediaPlayer class provides the controls for media playing but does not provide any view. However, a view can be realised with the help of MediaView. Here is a very minimal code to load and play audio/video in JavaFX.

A Quick Example

package org.mano.example;

import java.io.File;

import javafx.application.Application;
import javafx.scene.*;
import javafx.scene.media.*;
import javafx.stage.Stage;

public class SimpleMediaPlayer extends Application {

   @Override
   public void start(Stage stage) {

      Scene scene = new Scene(new Group(), 540, 209);
      stage.setScene(scene);

      stage.setTitle("Media Player");
      stage.show();

      String audio_source = "/home/mano/sonare.mp3";
      String video_source = "/home/mano/Tintin.mp4";
      File f = new File(video_source);
      Media media = new Media(f.toURI().toString());
      MediaPlayer mediaPlayer = new MediaPlayer(media);

      mediaPlayer.setAutoPlay(true);

      MediaView mediaView = new MediaView(mediaPlayer);
      ((Group) scene.getRoot()).getChildren().add(mediaView);
   }
   public static void main(String[] args) {
      launch(args);
   }
}

FX4
Figure 4: A media player example

JavaFX Web

JavaFX provides capabilities to interoperate HTML5 contents with the help of WebKit rendering engine. Similar to MediaView, WebView is used to manage WebEngine and display its content. The primary benefit is that JavaFX can harness HTML5’s rich Web content to create a Web user interface resembling the native desktop. This opens a new horizon in creating a desktop-like Web application in a JavaFX style.

A Quick Example

package org.mano.example;

import java.net.URL;

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.paint.Color;
import javafx.scene.web.WebView;
import javafx.stage.Stage;

public class SimpleMediaPlayer extends Application {

   @Override
   public void start(Stage stage) throws Exception {

      stage.setTitle("Displaying Java documentation");
      WebView browser = new WebView();
      Scene scene = new Scene(browser, 320, 250,
         Color.rgb(0, 0, 0, .80));
      stage.setScene(scene);
      URL url = new URL("home/mano/Java/java_doc/docs/index.html");

      browser.getEngine().load(url.toExternalForm());
      stage.show();
   }

   public static void main(String[] args) {
      launch(args);
   }
}

FX5
Figure 5: A Web page example

Conclusion

These are rudimentary sketches of what JavaFX can do. There are other extensive capabilities with respect to 3D APIs, custom UIs, Threading, Event handling, Observable collection, and so forth. Here, I have tried to give a little conceptual overview with supporting examples to visualize the ideas.

Nothing stays for long in technology until it goes through the rigors and pains, yet survives failures in delivering some tangible productive needs. However, success is optional without years of good work and tons of patience. JavaFX8, as we call it today, can rejoice but never rest as we move up the trajectory of its development. From interpreted JavaFX to a full-blown GUI library, the growth is commendable. Thanks to the well-grounded ambition of Chris Oliver’s (the man behind the machine, who almost single handed pushed the F3 project, which later was rechristened as JavaFX, in its initial phases), for he knows technology never survives because of its brilliance but because of its usability.

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Latest Posts

Related Stories