What is JavaFX?

JavaFX is a set of software APIs and tools that delivers desktop applications and rich internet applications (RIAs) that can run most anywhere Java runs. JavaFX applications run on Windows, MacOS, iOS, Android, Linux, and many other operating systems. JavaFX replaces Swing and the older AWT as Java SE’s GUI. Oracle is actively improving JavaFX, and likely will for many years to come.

That’s the simple version of what JavaFX is, but not a complete one. After reading the definition of JavaFX, you might still find yourself scratching your head and asking, What is JavaFX?

Obviously, this whole site is dedicated to answering that one question.

JavaFX is a modern windowing toolkit for use in Java 7 and above. JavaFX 8 showed up with the release of Java 8. Even though later versions of Java 7 shipped with JavaFX, it wasn’t until Java 8 that JavaFX became a natural citizen of the Java environment. By the time JavaFX shipped with Java 8, JavaFX had matured quite a bit. So, the JavaFX you see now is primed and ready for production Java environments, whether they be traditional Java applications built around JavaFX, or Applets in browsers compatible with Java through the use of a Java plugin.

JavaFX can be used like Java Swing was used, to create UI’s and UX by hand. You’ll find that JavaFX can be written very similarly to Swing and AWT were written—that is in pure Java. This makes a great starting point for old-time Swing and AWT developers that want to get a feel for JavaFX before jumping in to its more advanced features.

However, JavaFX can also be organized with a strong separation of presentation layer and business logic. JavaFX’s ability to support MVC and MVP is a great departure from Swing and AWT. JavaFX can (but does not have to) take advantage of a Markup Language called FXML for designing layout. JavaFX also has the ability to use Cascading Style Sheets (CSS), not too dissimilar to the more common web-style CSS many UX designers are used to. JavaFX written with a strong separation of business and presentation logic doesn’t feel a thing like Java’s earlier toolkits, and might be a bit difficult for older Java programmers to grasp at first. It’s a great design, but there is a slight learning curve involved with getting going with advanced JavaFX.

Separation of presentation layer and business logic in JavaFX is useful when you are creating applications large enough to require multiple developers or software engineers to work together. Separating the business logic and presentation layer allows coders to avoid stepping on each other’s toes while putting together a complex JavaFX app.

Keeping JavaFX app’s business logic and presentation layers separate also allows for easier upkeep and a longer software lifecycle for your JavaFX applications. This is where SceneBuilder and FXML come into play. You can use UX specialists that don’t even know Java to create and update your UI, and reserver the Java savvy members of your teams for work on the business end of your application’s code.

What Is JavaFX In Pure Java

No amount of explanation of what JavaFX is will be satisfying to a coder that wants an example of JavaFX. The following example does not take advantage of JavaFX’s separation of business and presentation logic. This is more geared at giving programmers a first glimpse at basic JavaFX. It’s all about helping you on your way to understanding what JavaFX is.

In Eclipse (or your favorite JavaFX friendly IDE) create a new Java project. Nothing fancy is needed for your JavaFX project. Just a standard Java project that supports Java 8 or above.

Create a class named SimpleFXExample in the package com.whatisjavafx. Modify your new JavaFX app’s code to read as follows.

package com.whatisjavafx;

import javafx.application.Application;
import javafx.stage.Stage;

public class SimpleFXExample 
extends Application {

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

  @Override
  public void start(Stage primaryStage) 
      throws Exception {
    // TODO Auto-generated method stub 
  }
}

 

If you are using Eclipse to do your JavaFX development, there is a chance you’ll run into an access restriction with JavaFX (and more specifically with using jfxrt.jar.) This is easily cleared up.

Find the project preferences. This will be different places depending on your OS. On Windows, it is under the Windows menu.

Forbidden Reference
Ignore “Forbidden Reference” to allow JavaFX to build.

Under the preference dialog, navigate to the Java -> Compiler -> Errors/Warnings section and change the forbidden reference rule from exception to ignore. That should allow you to compile JavaFX programs without an issue.

Your JavaFX program doesn’t do anything yet, but we’ll get to that shortly. You are well on your way to understanding what JavaFX is.

You are extending the javafx.application.Application class. That is the base class for every JavaFX application. Instead of starting your application in the main() method, JavaFX applications start in the start() method. A one liner is added to the main() method to launch the JavaFX application and then the real starting method is the start() method.

Next, lets put something useful in the start method.

package com.whatisjavafx;

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

/**
 * Make sure you extend
 * javafx.application.Application
 */
public class SimpleFXExample 
extends Application {

  /**
   * main() is just a starting place
   * to call launch()
   */
  public static void main(String[] args) {
    launch(args);
  }

  /**
   * start() is the minimum implementation
   * required by Application
   */
  @Override
  public void start(Stage stage) 
      throws Exception {
    
    /**
     * Labels are just places to display
     * text you won't be changing.
     */
    Label lbl = new Label("Hello World!!!");
    
    /**
     * VBox is a Region.
     * 
     * Regions (or Panes) are used to
     * group nodes like Labels.
     */
    VBox root = new VBox();
    root.getChildren().add(lbl);
    
    /**
     * One Stage can play host to various
     * Scenes over time. For this app,
     * we'll only have one Scene.
     */
    Scene scn = new Scene(root, 300, 100);
    
    /**
     * The stage is our window. Let's set
     * the title of our stage before adding
     * a scene.
     */
    stage.setTitle("Hi there!");
    stage.setScene( scn );
    
    stage.show();
  }
}

 

That’s a pretty simple, first JavaFX sample hello world app. You extend javafx.application.Application. You implement a start() method for your JavaFX Application. You they create a label that you add to a scene, that you add to stage.

JavaFX "Hi there!"
You should see a “Hi there!” titled window when you run this JavaFX application.

Now you’ve seen what pure Java based JavaFX is, let’s take a look at the more powerful JavaFX written from a MVC design perspective.

What is JavaFX FXML?

JavaFX gets really cool when you couple it with FXML. You can write FXML by hand, but we’ll save ourselves some time and create our FXML for the JavaFX app by using Scene Builder.

You could go through the pain of using Scene Builder without any Eclipse integration, but I recommend installing the e(fx)clipse JavaFX Tooling and Runtime. It just makes life too much easier. You can find that over at https://www.eclipse.org/efxclipse/install.html The Eclipse Market Place might not be up-to-date, so I recommend following the instructions over at the linked e(fx)clipse installation site.

So go ahead and install e(fx)clipse if you are planning to continue this JavaFX tutorial.

Now that e(fx)clipse is installed with any dependencies, go to the Eclipse menu and select …

File -> New -> Other…

This opens the New Project Wizard. Scroll down and select the JavaFX Project in the JavaFX folder as shown in the following image.

Project Selection Wizard
Select the JavaFX Project under the JavaFX folder.

Click next, and you will have the New Java Project configuration dialog. Choose a project name and select a JavaFX compatible JRE and click Finish.

JavaFX Project Creation Dialog
Fill in a JavaFX project name and choose a JavaFX compatible version of the JRE.

You now have a JavaFX project to work out of.

If you haven’t done so already, grab the Scene Builder app. It’s a free download. The main trick is that Oracle stopped releasing prebuilt copies of Scene Builder when they released Java 8 update 40. So, if you want a prebuilt copy, you can get one from Gluon.

Your new JavaFX project doesn’t come with much. It has an empty CSS file and a Main class that isn’t hooked up to any FXML.

Here’s the source for the default Main class.

package application;
	
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.layout.BorderPane;


public class Main extends Application {
  @Override
  public void start(Stage primaryStage) {
    try {
      BorderPane root = new BorderPane();
      Scene scene = new Scene(root,400,400);
      scene.getStylesheets().add(getClass()
        .getResource("application.css")
        .toExternalForm());
      primaryStage.setScene(scene);
      primaryStage.show();
    } catch(Exception e) {
		  e.printStackTrace();
    }
  }
	
  public static void main(String[] args) {
    launch(args);
  }
}

 

You may have noticed that their isn’t any FXML, yet. Let’s fix that, shall we?

Go ahead and open up Scene Builder. You should get a window like the following.

Empty Scene Builder Project
Scene Builder projects are really just FXML files.

Scene Builder builds FXML documents. I like to save the FXML documents in the directory (ie the package) that they are going to be used. That way they are already in the classpath.

I saved my new FXML document as main.fxml in the application package of my new JavaFX project. The FXML document starts as an empty file. You may need to refresh your Project Explorer in Eclipse for it to spot the new file in the application directory/package.

Just for easy comparison, drag a VBox from the Containers section on the left to the center area where it says, “Drag Library items here…”

Next, drag a Label from the Controls section on the left onto the VBox you just added. Change the text of the label to read, “Hello World!!!” You can do that directly on the Label or in the Inspector on the right hand side of Scene builder.

Save your changes to your main.fxml file. You can close the window and open up main.fxml. The main.fxml now contains the following code.

<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.control.Label?>
<?import javafx.scene.layout.VBox?>


<VBox 
 maxHeight="-Infinity"
 maxWidth="-Infinity" 
 minHeight="-Infinity" 
 minWidth="-Infinity" 
 prefHeight="300.0" 
 prefWidth="600.0" 
 xmlns="http://javafx.com/javafx/8.0.65" 
 xmlns:fx="http://javafx.com/fxml/1">
   <children>
      <Label text="Hello World!!!" />
   </children>
</VBox>

 

You can make changes to the FXML file directly, or make changes in Scene Builder. As long as the changes aren’t to odd, Scene Builder should understand your handwritten changes when you open the FXML file again.

Go ahead and change the preferred height to 100 and the preferred width to 300. You can do that from inside of Scene Builder or directly in the FXML file.

Rewrite the main file so that it looks like the following. (Let’s be honest. You’re going to cut-and-paste it.)

package application;

import java.net.URL;

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class Main extends Application {
  @Override
  public void start(Stage primaryStage) {
    try {

      // grabbing the main.fxml
      // from the classpath
      URL url = 
          getClass()
          .getResource("main.fxml");
      VBox root = FXMLLoader.load(url);

      Scene scene = new Scene(root, 300, 100);
      scene.getStylesheets()
      .add(
          getClass()
          .getResource("application.css")
          .toExternalForm()
          );
      primaryStage.setScene(scene);
      primaryStage
      .setTitle("Hi There ... Again!!!");
      primaryStage.show();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

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

 

If you run the JavaFX application, you’ll find it does roughly what the other one did. Also, adding some CSS to the CSS file could modify the look of your JavaFX window without any Java code being changed.

The main changes to recognize is this line.

getClass().getResource("main.fxml");

The getResource() method integrates the FXML descriptor file with the JavaFX application.

The other getResource() method loads the application.css file for use in formatting the look and feel of your JavaFX window.

Summary

What is JavaFX? JavaFX is a set of tools and API’s for creating UI’s. JavaFX can separate Business and Presentation logic completely when desired. However, JavaFX can also be written in pure Java for those times that you don’t need to separate team members taking care of presentation and business logic. JavaFX can go full MVC/MVP when needed.

JavaFX is what will replace Swing, though you can currently mix Swing with JavaFX, if needed to support legacy code.

FXML is what JavaFX uses for UI layout and setting up the whole UX for users. CSS is what JavaFX uses for changing the look and feel of your application after you have laid out the Stages, groups and nodes of the JavaFX project.

Hopefully you feel you have a slightly better idea of what JavaFX is!

One thought on “What is JavaFX?”

Leave a Reply

Your email address will not be published. Required fields are marked *