Java 8 New Features: JavaFX

The JavaFX is not really a new feature, but it’s the first time for it to make into a major Java release. JavaFX has a pretty long history as the next big thing for building cross platform GUI applications. Initially it has its own scripting language and hasn’t made its way in the Java community. The reason is simple: although the JavaFX has richer features on graphics, it does not seem worth learning a new language for it. For a long time, I was wonder why Sun didn’t use the investment to improve its Swing library which has much bigger audience than JavaFX.

Anyway, I think Oracle realized the problem and made the JavaFX usable in Java. This makes the adoption of JavaFX much easier, and using JavaFX is not much different from using another Java library like Swing. Better yet, the Swing and JavaFX can be mixed together. Given these development of JavaFX, I think it’s now a good time to try the JavaFX. That is why I spent some time to study it and wronte a few samples.

Bothered by SLOW Web UI to manage vSphere? Want to manage ALL your VMware vCenters, AWS, Azure, Openstack, container behind a SINGLE pane of glass? Want to search, analyze, report, visualize VMs, hosts, networks, datastores, events as easily as Google the Web? Find out more about vSearch 3.0: the search engine for all your private and public clouds.

With Java 8, the JavaFX is bundled together with JDK/JRE, so there is no need to download it separately as before. You can use Netbeans 8.0 to create new JavaFX projects. There are 4 templates in the project wizard and offers a good starting points. The following 3 samples are first created using the project wizard and further modified and simplified to make it Java 8 ready.

Standalone JavaFX Application

This sample is a pretty simple one with a button that when clicked prints out a message in console. It looks and feels like a Swing based application except that the components are different.

/* Copyright 2014 by Steve Jin. All Rights Reserved. */
 
package org.doublecloud.javafxapp;
 
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
 
public class JavaFXApp extends Application
{
  @Override
  public void start(Stage rootStage)
  {
    rootStage.setTitle("Hello DoubleCloud!");
 
    StackPane pane = new StackPane();
    Button btn = new Button();
    btn.setText("Say 'Hello DoubleCloud!'");
    btn.setOnAction(e -> System.out.println("Hello DoubleCloud!"));
    pane.getChildren().add(btn);
 
    Scene scene = new Scene(pane, 640, 480);
 
    rootStage.setScene(scene);
    rootStage.show();
  }
 
  public static void main(String[] args)
  {
    launch(args);
  }
}

JavaFX Markup Language

The GUI component structure can be described with XML based markup language called FXML. Similar technologies is used in Adobe Flex MXML and Microsoft XAML (Extensible Application Markup Language). The schema used may be different, the idea is the same.

As we’ll see, the GUI markup language is not enough for an application because it’s not good to define logics, say what if a button is clicked. These action logics are better off to be defined in programming languages like Java. As a general practice, there is a controller class for each FXML.

The following sample involves 3 files: one for main Java application to load the application, one FXML for defining the GUI, and one controller that holds logics for the FXML. Let’s check them out in that order.

/* Copyright 2014 by Steve Jin. All Rights Reserved. */
 
package org.doublecloud.javafxapp;
 
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
 
public class JavaFXAppWithFXML extends Application
{
  @Override
  public void start(Stage stage) throws Exception
  {
    System.out.println("res: " + getClass().getResource("."));
    Parent root = FXMLLoader.load(getClass().getResource("fxml_hello.fxml"));
 
    Scene scene = new Scene(root, 300, 275);
 
    stage.setTitle("FXML Welcome");
    stage.setScene(scene);
    stage.show();
  }
 
  public static void main(String[] args)
  {
    launch(args);
  }
}

The following is the FXML file that defines the GUI components. Its name shows in the above Java code.

<?xml version="1.0" encoding="UTF-8"?>
 
<?import java.lang.*?>
<?import java.util.*?>
<?import javafx.scene.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
 
<AnchorPane xmlns:fx="http://javafx.com/fxml/1" id="AnchorPane" prefHeight="400.0" 
            prefWidth="600.0" fx:controller="org.doublecloud.javafxapp.FXMLController">
  <StackPane fx:id="root">
    <Button text="Hello DoubleCloud" onAction="#handleClick"></Button> 
  </StackPane>
</AnchorPane>

In the FXML file, it specifies the name of the method to call when the button is clicked. Together with the controller name, the full call hierarchy is clearly defined. As a good practice, you want to place your FXML and the controller in the same folder.

/* Copyright 2014 by Steve Jin. All Rights Reserved. */
 
package org.doublecloud.javafxapp;
 
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
 
public class FXMLController
{
  @FXML protected void handleClick(ActionEvent event) 
  {
    System.out.println("Clicked 'Hello DoubleCloud!'");
  }
}

Mixing Java Swing and JavaFX together

With the popularity of Java Swing, it’s great to have Swing and JavaFX working together in one application. One big benefit from that is that you can continue to use whatever you’ve developed with Swing even you decided to move onto JavaFX.

/* Copyright 2014 by Steve Jin. All Rights Reserved. */
 
package org.doublecloud.javafxapp;
 
import java.awt.Dimension;
import javafx.application.Platform;
import javafx.embed.swing.JFXPanel;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javax.swing.JFrame;
 
public class FXSwingMain
{
  public static void main(String[] args)
  {
    JFrame frame = new JFrame("JavaFX2 + Swing");
 
    JFXPanel fxPanel = new JFXPanel();
    fxPanel.setPreferredSize(new Dimension(300, 250));
    Platform.runLater(() -> createScene(fxPanel));
 
    frame.setContentPane(fxPanel);
 
    frame.pack();
    frame.setVisible(true);
  }
 
  private static void createScene(JFXPanel fxPanel)
  {
    Button btn = new Button();
    btn.setText("Say 'Hello DoubleCloud'");
    btn.setOnAction(e -> System.out.println("Hello DoubleCloud!"));
    StackPane root = new StackPane( new Node[] { btn});
    fxPanel.setScene(new Scene(root));
  }
}

Although Swing and JavaFX can work together, they do not seem to co-exisit in a same thread. That is why the createScene() method is called in runLater().

Summary

The JavaFX in Java 8 is a nice feature and touted as the next for Java Swing. It seems pretty easy to get it up running. Allowing Swing and JavaFX running together would help smooth adoption. The only problem with JavaFX is that the related tooling is not quite there yet. For example, there is no good drag and drop tool for designing FXML while it’s common and mature for Swing design today.

This entry was posted in Software Development and tagged , , . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

2 Comments

  1. Posted October 29, 2014 at 9:40 am | Permalink

    Hi Steve,
    Some nice examples here. Thanks a lot.
    So, I have been looking at the part about defining the UI structure in the FXML file.
    I can see a few drawbacks to using this idea, but can you tell me what the advantages are?
    The drawbacks for me are:
    * Compilation errors – Say you miss-spell org.doublecloud.javafxapp.FXMLController or #handleClick in the FXML file. Would the IDE be able to warn you about this.
    * Debugging – Would the debugger be able to enter into the FXML file?
    * Dynamically changing the UI – Say you have some sort of player app with a “Start” button. You click “Start”, and then you want the text on the button to change to “Stop”.
    So, there are a few problems that I see with it. Can you tell me what advantages there are?

    Thanks a lot,
    Jim

  2. Posted October 29, 2014 at 8:04 pm | Permalink

    You are welcome Jim,

    Glad you find it useful.

    For the first two drawbacks, I think IDEs should address them. For the last one, I believe it’s possible to change the display text programmatically – the elements in the FXML are backed up by objects.

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

You may use these HTML tags and attributes <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

  • NEED HELP?


    My company has created products like vSearch ("Super vCenter"), vijavaNG APIs, EAM APIs, ICE tool. We also help clients with virtualization and cloud computing on customized development, training. Should you, or someone you know, need these products and services, please feel free to contact me: steve __AT__ doublecloud.org.

    Me: Steve Jin, VMware vExpert who authored the VMware VI and vSphere SDK by Prentice Hall, and created the de factor open source vSphere Java API while working at VMware engineering. Companies like Cisco, EMC, NetApp, HP, Dell, VMware, are among the users of the API and other tools I developed for their products, internal IT orchestration, and test automation.