JavaFX 2 Introduction

JavaFX 2 Framework – Introduction

Spread the word

To be continued!!!! Subscribe so that I can update you asap!

These days, we are starting a new project for realizing a Rich Internet Application (RIA). One of the first questions is: Which technologies and frameworks shall we use?

Introduction

You can create high quality GUIs using the JavaFX 2 Framework. It is simple and effective and that’s what I want to show you with this blog post. JavaFX 2 offers a wide range of programming interfaces with hardware-accelerated graphics and rich media engines that simplify development of data-driven enterprise software.

JavaFX was originally developed as a standalone language and got introduced in 2008 at JavaOne conference. The language itself became so popular that JavaFX 2 replaced JavaFX and was fully incorporated into the Java environment.

In the meantime, Sun was taken over by Oracle that further developed the technology. At that point in time they already announced JavaFX would become Swing’s successor in crime. For that reason, JavaFX 2 offers an interface to include Swing objects.

JavaFX 2 is already fully integrated in Java 7’s (update 6) runtime environment and available as add on for Version 6. According to Oracle’s official roadmap, its successor will become JavaFX 8 and will be released in 2014 and shall be fully completed with Java 9 in 2015. We’ll see.

Development Environment

Installation

As a basis for my development environment I use the latest Eclipse 4.2., the plug-in e(fx)clipse from Bestsolution.at (version 0.8) and the JavaFX Scene Builder 1.1 from Oracle itself.

In addition, you can either download the full software kit including all necessary plug-ins, or you go through “Help” in the main menu „Install New Software“ and add the repository “All in One” „http://downloads.efxclipse.org/p2-repos/releases/latest/“. I am using the full version in on a Java SDK 7 update 21 on a 32-bit basis.

To download the JavaFX Scene builder 1.1 go to www.oracle.com and get it from the official vendor.

Let’s get our hands on:

Eclipse Development Environment

Eclipse Development Environment

What is e(fx)clipse?

E(fx)clipse is a repository of tools that increase your JavaFX 2 application development by quite some time.

So, what are the most necessary tools:

  • Classpath container for JavaFX SDK and plug-in dependencies
  • Editor for JavaFX 2 FXML documents as add-on to the Java screen builder
  • CSS editor extension including JavaFX 2 specific attributes
  • JavaFX annotation implementation

Beyond that, e(fx)clipse offers JavaFX interfaces regarding other frameworks, such as EMF, Eclipse RCP, or OSGi.

JavaFX  2 mechanisms

JavaFX is often uses bindings, a powerful mechanism for expressing direct relationships between variables. When objects participate in bindings, changes made to one object will automatically be reflected in another object. But that won’t be the case in this chapter. Here we will mostly learn how to build a certain project. It sounds more complicated than it actually is.

Structure of a JavaFX project

The following is a simple JavaFX project that includes the listed objects:

  • JavaFX application class
  • JavaFX build configuration („build.fxbuild“)
  • FXML files with one or more graphic elements
  • FXML controller, that manages the code in the backend
  • CSS files for design adaption

 

JavaFX Wizard

JavaFX Wizard

The application class is a derivation of the Application class and inherits all methods, such as start(), init(), and stop(). Those methods can be overwritten. Furthermore, the main method starts with JavaFX application and calls the start() method.

In the build configuration, all meta- and start information specified to the JavaFX project are stated. Among other methods, the main class must be specified here. A build.xml can be generated from the build configuration, which in turn will then be used to derive the finished build of the project. The build contains an executable JAR file, as well as means to embed it in applet HTML code and Webstart JNLP file (“Java Network Launching Protocol”). This is the tool to start JavaFX as an external application from the browser.

FXML files can describe complete user interfaces or focus on individual sections with controls. The build the foundation to create Java objects in a later state.

Controller classes are assigned to manage properties and events of objects that are created. Those manage the corresponding views and models directly.

Last but not least, CSS files (“Cascading Style Sheet”) are created to adjust the design of JavaFX objects.

Structure of a JavaFX application (3.2)

The basis of each JavaFX application is the “JavaFX main class” that is an extension f the Application class. As mentioned earlier, this class inherits the methods start(), stop() and init() whereby start() is an abstract class.

An abstract class is a class that is declared abstract—it may or may not include abstract methods. Abstract classes cannot be instantiated, but they can be subclassed. – http://docs.oracle.com/javase/tutorial/java/IandI/abstract.html

So start () is called within the implicit and general Java main method through launch() and passes an optional start parameter.

The life cycle of a JavaFX applicaction

The life cycle of a JavaFX applicaction

At the very beginning start() obtains a “primaryStage”, which is the main container for the application. A Stage can have a Scene that includes a Pane.

The JavaFX window scaffold

The JavaFX Window Scaffolding

The Scene Graph

To build a JavaFX application you need to understand how the JavaFX Scene Graph API handles the graphical user interface. The scene graph is a tree structure that defines an application’s user interface. To build the user interface you are effectively filling the tree with graphical elements. The core set of classes for the JavaFX Scene Graph are held in the JavaFX.scene package. Nodes can be placed into one of two categories:

  • Branch Nodes – These are objects which have the Parent class as part of their hierarchy. The Parent class allows for the possibility of having child nodes. For example, Group objects (a collection of nodes), Region objects (i.e., StackPane, FlowPane) can have child nodes. But it also includes Control objects (e.g., Button, ChoiceBox) which can’t have child nodes.

Leaf Nodes – These nodes cannot have child nodes. For example, Shape objects (e.g, Circle, Rectangle), ImageView objects (for displaying images) and MediaView objects (used for playing music or video).

Scene Graph Tree

Scene Graph Tree

Example of a JavaFX Scene Graph Tree

 

Example „HelloWorldFX“

For this example we are going to use the wizard.

1) Create a new JavaFX project “New”-> “JavaFX Project”

2) Create a new JavaFX Main Class ”MainHelloWoldFX”

3) Copy and paste the following code:

public class MainHelloWoldFX extends Application { 
 @Override 
 public void start(Stage primaryStage) { 
  GridPane gridPane = new GridPane(); 
  Label label = new Label("Name"); 
  TextField textfield = new TextField(); 
  Button button = new Button("Press"); 
  gridPane.add(label, 0, 0); 
  gridPane.add(textfield, 1, 0); 
  gridPane.add(button, 1, 1); 
  gridPane.setPrefWidth(400); 
  gridPane.setHgap(50); 
  gridPane.setVgap(20); 
  Scene scene = new Scene(gridPane); 
  primaryStage.setWidth(400); 
  primaryStage.setHeight(400); 
  primaryStage.setTitle("Hello World"); 
  primaryStage.setScene(scene); 
  primaryStage.show(); 
 } 
 public static void main(String[] args) { 
  launch(args); 
 } 
}

In this example a grid called „gridpane“ is invoked that includes a control “label”, “textfield” und a “button”. Based on this grid we call the “primaryStage” into the same scene.

4) Start the application

Basic objects

Basically, all JavaFX objects implemented in a scene inherit the properties of a node, in other words, each object in a scene is a JavaFX node. Nodes include fundamental properties such as position, translation, scaling and visibility.
Each node obtains an ID so that CSS can address a node and alter its properties. Not only CSS but event handling of all user I/O actions like mouse button, Keyboard input, Drag & Drops is located at the Node class.

Controls

In addition, each JavaFX user element is an expression of the Control class. Controls are JavaFX specific controls. They possess the properties:

  • Minimum height and width
  • Preferred height and width
  • Maximum height and width

An added value is the option to apply tooltips as well as context menus. The control class also carries the true height and width of the element during run time.

Controls are:

  • Label
  • Textfield
  • ChoiceBox
  • TebleView

FXML files

Here is an example of a FXML file:

<?xml version="1.0" encoding="UTF-8"?> 
<?import java.lang.*?> 
<?import javafx.geometry.*?> 
<?import javafx.scene.control.*?> 
<?import javafx.scene.layout.*?> 
<?import javafx.scene.layout.VBox?> 
<VBox xmlns:fx="http://javafx.com/fxml"> 
<children> 
<HBox fx:id="hbox_input" alignment="CENTER_LEFT" prefHeight="37.0" prefWidth="368.0" spacing="10.0"> 
<children> 
<Label fx:id="label_name" contentDisplay="LEFT" text="What´s your name?"> 
<TextField fx:id="textfield_name" prefWidth="100.0" /> 
</children> 
</HBox> 
<HBox fx:id="hbox_output" prefHeight="29.0" prefWidth="368.0" spacing="2.0"> 
<children> 
<Label id="label_output" fx:id="label_Hello" text="Hello" /> 
<Label id="label_output" fx:id="label_outputname" text="" /> 
</children> 
</HBox> 
</children> 
<padding> 
<Insets left="5.0" right="5.0" /> 
</padding> 
</VBox>

The root element in this file is calles VBox and the result is this:

FXML VBox

FXML VBox

Controller

In order to push and pull data from and to the objects during runtime you use Controller classes. Controller are bound to the JavaFX control elements through annotations.

In your controller class you can implement the Initializable interface. This interface is designed to call initialize() immediately after the FXML file has been loaded successfully.

A working example is:

public class SampleVBoxController implements Initializable { 
@FXML 
private HBox hbox_input; 
@FXML 
private HBox hbox_output; 
@FXML 
private Label label_Hello; 
@FXML 
private Label label_name; 
@FXML 
private Label label_outputname; 
@FXML 
private TextField textfield_name; 
@Override // This method is called by the FXMLLoader when initialization is complete 
public void initialize(URL fxmlFileLocation, ResourceBundle resources) { 
assert hbox_input != null : "fx:id=\"hbox_input\" was not injected: check your FXML file 'SampleHBox.fxml'."; 
assert hbox_output != null : "fx:id=\"hbox_output\" was not injected: check your FXML file 'SampleHBox.fxml'."; 
assert label_Hello != null : "fx:id=\"label_Hello\" was not injected: check your FXML file 'SampleHBox.fxml'."; 
assert label_name != null : "fx:id=\"label_name\" was not injected: check your FXML file 'SampleHBox.fxml'."; 
assert label_outputname != null : "fx:id=\"label_outputname\" was not injected: check your FXML file 'SampleHBox.fxml'."; 
assert textfield_name != null : "fx:id=\"textfield_name\" was not injected: check your FXML file 'SampleHBox.fxml'."; 
// initialize your logic here: all @FXML variables will have been injected 
} 
}

Es mentioned earlier, the annotation „@FXML“ assigns variables to control elements. In this example “fx-id” correlates the FXML elements with the variables. The initialize() method checks wether the applying Asserts if the control elements are linked properly.

FXMLLOADER

The FXMLLOADER class offers an interface between FXML files and the source code. It assigns the files to an object during runtime. In addition, if you want you can add a controller object.

A typical FXMLLoader call looks like this:

FXMLLoader fxmlLoader = new XMLLoader(getClass().getResource("/SampleVBox.fxml")); 
SampleVBoxController controller = new SampleVBoxController(); 
fxmlLoader.setController(controller); 
VBox sampleVBox = (VBox) fxmlLoader.load();

Further JavaFX Elements

Properties and Bindings

JavaFX includes primitive data types that each have a wrapper class. This wrapper class implements the property interface, for example SimpleStringProperty, SimpleIntegerProperty. However, the Java FX property model has been extended and is based on the proven JavaBeans model.

Properties are usually used in combination with bindings, a mechanism for fast and and direct relationships between two variables. There are two different types of bindings, the High-Level binding and Low-level binding. The high-level binding is the simpler and faster method, while the low-level method provides additional flexibility and complexity.

label_outputname.textProperty().bind(textfield_name.textProperty());

This simple binding example enables us to do basic I/O. That means, you type into the textfield “textfield_name”, which changes the input for label “label_outputname”.

Bindings may extend dependencies over a variety of properties. For instance:

IntegerProperty int1 = new SimpleIntegerProperty(2);
IntegerProperty int2 = new SimpleIntegerProperty(4);
NumberBinding sum = Bindings.add(int1, int2);
System.out.println(sum.intValue());

Eventmanagement

To be continued!!!! Subscribe so that I can update you asap!

Comments (6) Write a comment

  1. Pingback: Java desktop links of the week, October 7 « Jonathan Giles

  2. I just started using javafx, your work helped me alot to understand some basic principles. I loved the simplicity and the clarity, good job. Thank you for sharing!

    Reply

  3. Hi there, that’s a cool tutorial. I am currently working on a javafx that will run on a raspberry pi. I have to make use of the PI4j library (pi4j.com).
    Do you mind explaining how one can make use of external libraries unto a javafx. I have been trying to get stuff working with it but I keep on getting errors about event Handlers I’m not sure what’s wrong.

    Thank you in advance

    Reply

Leave a Reply

Required fields are marked *.