JavaFX

from Wikipedia, the free encyclopedia
JavaFX
Basic data

developer Oracle
Current  version 14
( March 10, 2020 )
operating system Windows , macOS , Linux
programming language Java
category Framework
License GPL with GPL linking exception
OpenJFX on java.net and openjfx.io

JavaFX is a framework for creating cross-platform Java - applications . It is a Java specification from Oracle and aims to facilitate the professional creation and distribution of interactive , multimedia content and graphical user interfaces (GUIs) across all Java platforms .

Until 2014 AWT and Swing were the standard solutions for graphic applications under Java. However, these were getting on in years. There were gaps in the area of ​​media and animation , which is now in demand with modern graphical interfaces. Instead of investing in the further development of AWT / Swing, Oracle decided to completely redesign the GUI level with JavaFX.

JavaFX is particular to a scene graph (engl. Scene graph ) which manages the individual components of a GUI. With FXML it also enables a declarative description of graphical interfaces on an XML basis. The Scene Builder is a graphical tool that simplifies the creation of FXML files. Web technologies such as CSS can also be used for the design by embedding them in the FXML code.

Since JavaFX offers all APIs for modern interfaces and is not dependent on AWT / Swing, it forms a complete media stack. JavaFX has direct access to all 2D / 3D skills of modern graphics processors . JavaFX can also be used to program everything that was previously preferably implemented with Flash .

The JavaFX runtime environment was part of every x86 Java SE installation from version Java SE Runtime 7 Update 6 to 10.

Development history

The history of JavaFX is not particularly straight forward. Originally, Sun / Oracle wanted to position JavaFX as a Flash replacement on the Internet, but the combination of HTML5 and CSS3 and JavaScript was too attractive. Nowadays it is mainly a GUI toolkit for classic client applications .

Version 1

JavaFX was announced in May 2007 and presented at the JavaOne developer conference in May of the following year . On December 4, 2008, Sun officially released JavaFX 1.0 as a developer kit for Windows and macOS . The JavaFX 1.0 release appeared together with the JavaFX Script programming language . This language made it easy to build hierarchical object graphs and offered a good syntax for object binding, with which states could be synchronized.

Version 1.2 was released in June 2009. Among other things, it contained customizable UI controls, additional layout classes (Tile, Stack, Flow, ClipView, Panel), and support for RSS / Atom feeds. It is not backwards compatible. Linux and Solaris have only been supported since this version . Version 1.3 (code name SoMa) was released on April 22, 2010. The most obvious innovation is a sometimes enormous increase in performance. Also new is JavaFX TV, an official CSS API for designing JavaFX controls, some new, desired controls and support for 3D. Version 1.3.1 was released on August 21, 2010 and improved the progress bar when starting up and debugging in Netbeans 6.9.1.

Version 2

JavaFX 2.0 appeared as announced in the third quarter of 2011. JavaFX Script is not used in this version, "because Oracle did not want to build another programming language, but a pure Java API that developers could then address from various existing scripting languages." JavaFX Script APIs ported to Java. Hardware rendering has also been optimized in JavaFX 2.0 so that games and complex 3D displays should now be possible. JavaFX 2.0 renders HTML and JavaScript content using the WebKit library. In the course of the release of the new version, Oracle announced that it would continue to develop JavaFX as an open source project within the scope of the OpenJDK .

JavaFX developed more and more to the alternative of Swing / AWT. JavaFX 2.2 was released in August 2012. This was integrated into the JRE / JDK 7 Update 6. The step was unusual because such large additions had never been made as an update in the JRE / JDK.

The development towards Open Source resulted in OpenJFX, which, together with the OpenJDK , allows a completely free Java system with a GUI stack to be built under the GPL .

Version 8

With the move into the Java 8 release, JavaFX also made the release jump from 2 to now 8. JavaFX 8 brings some innovations with it. For example, it offers lambdas as a new language construct. One of the big innovations is also the JavaFX-UI-Toolkit, which is delivered with Java 8 as the recommended UI-Toolkit. The toolkit offers with FXML u. a. an XML -based language for creating user interfaces.

With version 8u33, Oracle's ARM support for JavaFX was discontinued. Therefore JavaFX is no longer included in the official Java distributions for ARM.

Roadmap

"Mobile first" and "Web first" motivates Oracle to discontinue support for JavaFX, probably in 2022. Further development will then take place as a separate open source module, for which Oracle is already working with interested parties.

architecture

The architecture of JavaFX is completely new and in particular is not based on Swing or AWT. However, this also means that JavaFX and AWT / Swing cannot simply be mixed (even if there are solutions for it). JavaFX offers a complete API for modern interfaces. The main packages of this API are:

Package description
javafx.animation Classes for animation based on transitions
javafx.application The classes for the basic life cycle of an application
javafx.collections Essential JavaFX collections including utilities
javafx.event The basic framework for JavaFX events and their handling
javafx.fxml Classes for loading an object hierarchy from a markup structure such as FXML
javafx.geometry Classes for geometric operations on two-dimensional objects
javafx.scene The base classes for the JavaFX Scene Graph API and the parent package of the individual components and elements. It contains sub-packages like canvas, chart, control, effect, image, input, layout, media, paint, shape, text, transform, web etc.
javafx.stage Top-level container classes for JavaFX content
javafx.util Various utilities and auxiliary classes

The following graphic shows the architecture of JavaFX as it is officially represented by Oracle:

Javafx-architecture.svg

As with every Java application, the JavaFX also has the Java Virtual Machine (JVM) on the lowest level , which is responsible for executing the Java bytecode . Normally, each started Java program is executed in its own virtual machine (VM).

The corresponding development tools for Java or JavaFX are provided in the Java SE Development Kit (or just Java Development Kit, JDK for short). Based on this, there are numerous extensions, some of which have been used with Java for a very long time, such as Java 2D for drawing two-dimensional shapes.

Prism is the new rendering engine that makes use of the graphics hardware (if supported). Among other things, it also makes properties of Java 2D and various graphic effects such as shadows, reflections, transformations or animations available on a high level. It is rendered with OpenGL under Linux and macOS , while Direct3D is used under Windows . If the graphics hardware is not supported, a software fallback to Java 2D is used.

The Glass Windowing Toolkit provides low-level operating system routines, such as window management, timers or event management. It serves as a platform-dependent layer that connects the JavaFX platform with the operating system.

The media engine is based on GStreamer and offers extensive support for audio and video. The Web Engine enables web content to be embedded in JavaFX applications. This includes HTML rendering based on the WebKit engine, hardware-dependent rendering via Prism and the option of DOM access and manipulation of the DOM.

The Quantum Toolkit links Prism, Glass Windowing Toolkit, Media Engine and Web Engine and makes them uniformly accessible to the JavaFX APIs. The JavaFX API and the Quantum Toolkit encapsulate the details of the lower levels and hide them from the user. In principle, a JavaFX developer does not need to know how the lower levels work.

Structure of a JavaFX application

JavaFX lifecycle

JavaFX application life cycle

JavaFX applications extend the base class Application , the lifecycle methods such as init(), start()or stop() inherited . These methods can (or must) be overridden in the JavaFX application . The JavaFX launcher takes care that these are called accordingly. So JavaFX applications require no mainmethod: The own static main(String[])method directs the static launch(String[])method of Application- class on and gives her all call parameters . Since the class method launch(...)knows which class it was called in, it creates an instance of that class and then calls the lifecycle methods .

The life cycle of a JavaFX application is as follows:

  1. When the application starts, the JavaFX runtime first constructs an instance of the Applicationclass.
  2. Now the init()method of the created instance is executed. This method is implemented as empty by default and does not necessarily have to be overwritten. For example, the call parameters can be read out here. However, no UI elements may yet be created here.
  3. Next, the method is start(javafx.stage.Stage)called, which must be overridden by any JavaFX application. JavaFX transfers a stage to the method, which roughly corresponds to the task of a main container and can best be compared with the start window.
  4. The JavaFX runtime now waits until the application is terminated. This can be done as follows:
    • by calling the method Platform.exit()
    • by closing the last window and setting the attribute implicitExitto Platform on true.
  5. Now the runtime calls the stop()method before the Java process is stopped. Again, this method does not necessarily have to be overwritten.

The stage

The stage forms the framework for the actual content. The Scene class manages the scene graph. This is a rooted tree made up of nodes. Parent nodes contain additional nodes, while the leaf nodes represent the visible elements of the GUI (button, text field, slider, etc.).

The start(...)method is a Stagepass. The parameters of start(...)is thus the type javafx.stage.Stage. This class is the top-level JavaFX container that is always constructed by the platform - as a parameter of the start(...)method. This can best be compared to the start window . Additional stage objects can also be created in an application .

The stage can be used to make a number of scenes or (Engl. Scenes ) to present. The naming of the base classes Stageand Sceneis similar to the theater: The Stage is the stage that is listed on the scene. It forms the framework for the actual content.

As with a window, there are numerous setting options for a stage object using appropriate methods, for example

  • setWidth(double value)and specify setHeight(double value)the height and width of the stage, and
  • setTitle(java.lang.String value) sets the title of the window.

The StageStyledetermines the appearance of the window. The default value is DECORATEDthat which displays a window with a border and controls depending on the operating system and a white background. Most of the properties of a Stage object, however, are read-only because they are changed by the underlying platform.

The scene

One or more scenes of the type javafx.scene.Sceneare usually presented on the stage . This class is the container for all content in a scene graph that manages the individual components of a GUI .

From graph theory point of view of the scene graph is a Rooted tree consisting of nodes (German node exists). As inner nodes there are parent nodes that can contain further nodes (nodes) as children. A sheet (Engl. Leaf node ), however, has no further children. The leaves now represent the visible elements of the GUI (e.g. buttons, text windows and sliders), the parent nodes the invisible structural elements (e.g. BorderPane, HBox and VBox). An application must have the root node (engl. Root node ) for the scene graph to specify. This is something like the origin from which the entire scene develops. There is an argument for the constructor of an Sceneobject for this. The Sceneobjects must be created and modified in the JavaFX application thread .

This Sceneis also the link between the window made available by the operating system and the scene graph. If, for example, the window is enlarged, the tries Sceneto pass this change on to the root node: isResizableTo do this, it calls the method on the root node to find out whether the node wants to react to size changes. If the node truereturns, it will change Sceneit to the new size, it falseleaves it at.

With the command stage.setScene(scene), the scene graph comes Sceneonto the stage via the class . All graphic objects of a JavaFX application are present at any point in time, i. H. they don't just exist at the time of drawing.

Nodes

Hierarchy of the node classes in JavaFX.

All objects in the scene graph are of the type Node. These therefore form the content of the scene graph. Each node and each element in the scene graph is in turn a subtype of the abstract class Node.

A subclass of Nodeis Parent. The parent nodes are the base class for all nodes that contain additional nodes as children, i.e. are containers. There are subclasses of Parent:

  • The class Groupcombines several elements in one node. It enables, for example, transformations and effects to be applied to the group and delegated from it to all elements (children) of the group. The Groupnode runs one ObservableListof children. The method getChildren()can be used to call up the list of children, which can then be added using getChildren().add(element)further elements. One Groupdoesn't care about the children's positions and can't be adjusted via CSS.
  • The class Regionforms the base class for all controls and layouts and extends the base class with many options for styling via CSS. From Regionthere is a lower class Pane, which are the children through public methods to the outside. The derived class BorderPane, for example, positioned above the children ( top ), left ( left ), right ( right ), from below ( bottom ) and center ( center ).
  • The class Controlextends the class Region. It is the base class for components that allow user input in some form. This includes, for example, buttons or labels. Each control component can in turn be edited optically using CSS.

JavaFX comes - like Swing - with a set of standard components in the package javafx.scene.controland has Controlas a base class. The following overview lists the most important controls that are available in JavaFX:

Control use
Label The label is one of the simplest controls. It consists of a text and any other node for declaration. An image is often used for this.
Hyperlink Corresponds to an HTML - hyperlink and is displayed by default as blue underlined text.
Button A button can be pressed. The selection status is retained.
Radio button A selection button for individual selection from a group of radio buttons . The selection status is retained until another button in the same group is selected.
ToggleButton A selection button that exists in two states: selected and not selected. Behaves in a similar way to a CheckBox or a RadioButton.
CheckBox A checkbox is a selection box with three possible states: undefined, checked and unchecked. The selection status is retained until it is changed.
ChoiceBox A selection list for selecting an individual item from a preferably short list.
TextField Single-line free text input field with cursor control and selection.
TextArea Multi-line free text input field with cursor control and selection.
ListView Standard component for displaying lists of objects.
TableView A table component that is made up of a series of columns (TableColumns). Individual cells are represented as TableCell.
TitledPane A partial dialog that can be opened and closed.
ScrollPane Serves for displacing and presenting a section with horizontal and vertical scroll bar ( scroll bar ).

First of all, controls are just nodes that can be added to the SceneGraph and then displayed. Of course, the corresponding classes for UI controls provide various specific properties and methods to support typical interactions with users.

Program examples

Hello JavaFX World!

The following program example shows a typical Hello World program in JavaFX:

package application;

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

public class Main extends Application {

	@Override
	public void start(Stage primaryStage) {
		Label label = new Label("Hello JavaFX World!");

		StackPane root = new StackPane();
		root.getChildren().add(label);

		Scene scene = new Scene(root, 400, 300);

		primaryStage.setTitle("Hello JavaFX World!");
		primaryStage.setScene(scene);
		primaryStage.show();
	}

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

The class Mainis Applicationderived from the class . The own main(...)method forwards to the launch(...)method of the Application class. In the created instance of the Applicationclass, the init()method is first executed, which remains empty here as the default .

Next, the start(...)method is executed which, as here, must be overridden by every JavaFX application. JavaFX passes the method one Stagethat can be compared with the start window. start()The following steps are now carried out within the method:

  • A simple label control is labelcreated. The text to be displayed "Hello JavaFX World!" Is passed directly to the constructor here.
  • Now a StackPanename is rootcreated. This places all child elements on top of each other in the order they are added. By default, the components are centered in the StackPane. The root.getChildren().add(label)previously created is now Label labeladded via .
  • Now one is Scene scenecreated that can then be Stageloaded onto the . The application must specify a root node for the scene graph. In this example this is the rootobject of type StackPane. In addition, the constructor is given a specific display size ( ).
  • In the next step, primaryStage.setTitle("Hello JavaFX World!")the title of the application window is also set to “Hello JavaFX World!”. Most important, however, is the assignment of the scene scenethat refers to the actual content. The show()method now tries to display the window by setting the visibility to true.

Cycle of Life

package application;

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

public class CycleOfLife extends Application {

	@Override
	public void init() {
		System.out.printf("Die Methode init(), aufgerufen im Thread %s%n",
				Thread.currentThread());
	}

	@Override
	public void start(Stage primaryStage) {
	   System.out.printf("Die Methode start(), aufgerufen im Thread %s%n",
                  Thread.currentThread());
	   Platform.exit();
	}

	@Override
	public void stop() {
		System.out.printf("Die Methode stop(), aufgerufen im Thread %s%n",
				Thread.currentThread());
	}

	public static void main(String[] args) {
		System.out.printf("Die Methode main(), aufgerufen im Thread %s%n",
				Thread.currentThread());
		launch(args);
	}
	
}

The program provides roughly the following output:

The main () method, called in the thread thread [main, 5, main]
The init () method, called in the thread thread [JavaFX-Launcher, 5, main]
The start () method, called in the thread thread [JavaFX Application Thread, 5, main]
The stop () method, called in the thread thread [JavaFX Application Thread, 5, main]

The main(...)method of CycleOfLifecalls Application.launch(...)and an instance of the Applicationsubclass is created in the JavaFX application thread . The init()method is called in the JavaFX Launcher thread , which is the thread that starts the application. To execute the start()and stop()methods, JavaFX creates a thread called the JavaFX Application Thread . The creation of Stageand Sceneobjects and modifications to the scene graph must take place within this JavaFX application thread .

Event handling

The event handling of JavaFX is the consistent further development of the event handling under the AWT and Swing or Java itself, but also on the web. Modern graphic programs are very event-oriented. You therefore need mechanisms that react to the occurrence of events.

Ralph Steyer explains the basic idea of ​​event handling as follows:

One object can fire an event object and another object registers itself for a reaction to it (a so-called event listener), such as in the case of a spark, in which a transmitter sends a message with its radio on a certain frequency and a receiver sends its radio tuned to that frequency, receives the message. In exactly the same way, the recipient can react to a notification about an event or ignore the message. The concrete event handling is therefore decided in the listener object.

JavaFX events

The package javafx.eventcontains the relevant classes and interfaces for event handling in JavaFX. Basically, a concrete event an instance of the class javafx.event.Eventor one of its subclasses such as DragEvent, KeyEvent, MouseEventor ScrollEvent.

When an event occurs, an internal mechanism is used to determine which node is the target of an event object. For mouse events, for example, the target is the node at the location of the mouse pointer. From the selected event target there is an event dispatch chain that goes up to the root of the scene graph.

It always tries first to handle the event in the innermost element in which it occurred. This requires a suitable event handler (or some other handling structure). After that, the element of the event object to the next highest object in the tree forwarded etc. One speaks in this context of event bubbling, as the event object like a bubble (Engl. Bubble ) to the root of the scene graph rises. If this cannot be treated to the root, it will be destroyed. This is quite the rule, as many events such as moving the mouse pointer by a few millimeters do not force a specific reaction from the application.

Event handler

If any node in the route of the event object has registered an event handler, the event is consumed. The task of the programmer is therefore to catch the event accordingly and to implement the reaction to it. Event handlers basically implement the EventHandlerinterface, which handle()forces a method described there to be overwritten . This is where the actual reaction to the event that has occurred belongs. Often the event handler is created and registered as an anonymous class , with the handle()method implemented directly to provide the desired actions. This method then contains an event object of the relevant type as a parameter.

The following two methods provide a general way of adding or deregistering an event handler to a node object:

  • addEventHandler(EventType<T>, EventHandler<? super T>) to add a handler
  • removeEventHandler(EventType<T>, EventHandler<? super T>) to log off a handler.

The first parameter specifies the specific event to which you want to react, and the second parameter specifies the event handler itself.

For one, it Button btncould look something like this:

btn.addEventHandler(ActionEvent.ACTION, new EventHandler<ActionEvent>() {
	@Override
	public void handle(ActionEvent event) {
		// do something here
	}
});

In addition, the component classes also offer their own setter methods for specific events, which have the following format:

setOnEventType(EventHandler handler)

Here indicates EventTypethe type of event. For example, there is Buttonthe following method setOnAction(EventHandler<ActionEvent>):

btn.setOnAction(new EventHandler<ActionEvent>() {
    @Override
	public void handle(ActionEvent event) {
		// do something here
	}
});

Dynamic data structures with change notifications

In JavaFX individual values are not only observierbar but also dynamic data structures that are in the package javafx.collectionsare: ObservableList, ObservableMapand ObservableSetare derived from each Observable interface , and add each method adds to the appropriate ChangeListenerregister. So the new data structures extend the java.utildata structures List, Setand Mapand can report changes.

For ObservableListexample, there is an interface for one ListChangeListenerthat reacts to changes in the observed list. The class ListChangeListener.Changerepresents a change that is made to such a list. With

observableList.addListener(new ListChangeListener(){/* do something here */});

the listener is then registered for changes to the list.

Functional interfaces and lambda expressions

A lambda expression is a nameless (anonymous) method that can be passed (as an object). The term goes back to the lambda calculus , a formal language for investigating functions (see also functional programming ). Lambda expressions in Java typically include parameter lists, a return type, and a body:

(Parameterliste) -> {Anweisungen;}

Lambda expressions therefore describe function objects. A function that returns the sum of two arguments can be expressed as follows:

(i,j) -> {i+j;}

The specification of the parameter types is only necessary if the compiler cannot infer it itself from the context of the expression. Lambda expressions help to avoid the often difficult to read, long declarations of inner, anonymous classes.

In Java, interfaces that have only one operation (abstract method) are called functional interfaces . A function descriptor describes this method. An abstract class with just an abstract method, however, is one not as a functional interface. A lambda expression is an example of such a functional interface. It is obvious that functional interfaces prescribe exactly one abstract method, because if there were several, a lambda expression would have to offer several implementations or somehow prefer one method and neglect others. Of course, types and exceptions must also match. So there is not an abbreviation via a lambda expression for every interface.

For example, the interface can be ActionListenerimplemented as an anonymous class with only a single method by handle()overriding its abstract method. With newis then formed a copy and passed as parameters accordingly (See "Event Handler"). Instead of an inner anonymous class, a lambda expression can now be used:

btn.setOnAction((event) -> {/*do something here*/});

A setOnAction(...)complete object is no longer created as the argument of the method new. Instead, the (any) identifier of the method argument and the statements are ->noted separately by an arrow operator . So a short form of the complete method implementation of the called handle()method is noted.

Properties and data binding

Properties and data binding are two powerful language mechanisms in JavaFX with which relationships between variables can be designed. Usually they are used to (mutually) update values. For example, the user operates a slider that controls the width of a rectangle, and depending on the value set, the widthvalue of the data model must be updated and the area of ​​the rectangle recalculated. In order to compare the data with one another, there is therefore the concept of properties and data binding.

Properties are the basic building blocks in JavaFX for processing and communicating value changes. They form the basis for convenient data binding. A property is a data container that also enables change notifications. Other classes interested in changes can register as listeners. A bond is also referred to as dependency or dependency .

The binding APIs are divided into two categories in JavaFX:

  • The high-level API: Provides an easy way to create bindings for most situations. In particular, code completion is provided for this in IDEs such as NetBeans.
  • The low-level API: This API is very flexible, lean and fast and offers extended options if the high-level API is not enough.

The package javafx.beans.propertydifferent property classes are defined, such as for encapsulation of int, long, float, double, booleanand String. The properties implement the interface Observableor for notification of changes ObservableValue<T>. For example, instead of the primitive data type double, a new type is DoublePropertyused that double"wraps" the primitive type . In addition to the getter and setter methods , the JavaFX properties also have an additional method that ends with a property and returns the property object.

The following example comes from the Java documentation from Oracle and defines a class called Bill(German invoice ), which implements a single property called amountDue(German due amount ):

package application;

import javafx.beans.property.DoubleProperty;
import javafx.beans.property.SimpleDoubleProperty;

public class Bill {

	// Definiere eine Variable um die Property zu speichern
    private DoubleProperty amountDue = new SimpleDoubleProperty();

    // Definiere die Getter-Methode für den Wert der Property
    public final double getAmountDue() {
    	return amountDue.get();
    }

    // Definiere die Setter-Methode für den Wert der Property
    public final void setAmountDue(double value) {
    	amountDue.set(value);
    }

    // Definiere einen Getter für die Property selbst
    public DoubleProperty amountDueProperty() {
    	return amountDue;
    }

}

The amountDueobject is an instance of the class javafx.beans.property.DoubleProperty. It is privatemarked as to encapsulate it . According to the naming convention for accessing properties, there are the following methods:

  • The getAmountDue()method is the default getter that amountDuereturns the current value of the property. The return value of this method is double(and not something DoubleProperty). The getter method should be finaldeclared as.
  • The setAmountDue(double)method is also finaldeclared as and enables the value of the property to be set externally. Your parameter is also double.
  • The amountDueProperty()method defines the getter of the property and returns the property itself. It is a new convention made up of the name of the property (here amountDue ) and the word property .

Properties are of particular interest when one observes their changes. In the Java event model there are so-called event triggers ( event sources ), such as buttons or sliders. These events can originate from users of the graphical user interface, but can also be traced back to their own triggers. In addition to the event triggers, there are a number of interested parties, so-called listeners, who want to be informed when a certain event occurs. In this case, there is a ChangeListener( javafx.beans.value.ChangeListener) addListener()for the properties, which can be appended to the property via the method that is returned with the corresponding getter method.

To illustrate a ChangeListener, Mainan instance of electricalBillthe class Bill(see above) is created in the Java documentation in the class :

package application;

import javafx.beans.value.ObservableValue;
import javafx.beans.value.ChangeListener;

public class Main {

    public static void main(String[] args) {
    	Bill electricBill = new Bill();

    	electricBill.amountDueProperty().addListener(new ChangeListener<Object>(){
    		@Override
    		public void changed(ObservableValue<?> o,Object oldVal, Object newVal) {
    			System.out.println("Electric bill has changed!");
    		}
    	});

        electricBill.setAmountDue(100.00);
    }

}

The output appears in the console Electric bill has changed! . The listener noticed that electricBill.setAmountDue(100.00)the value of the amountDue property was changed and the corresponding message was changed(...)output via the method.

The high-level APIs are the easiest and fastest way to use bindings. They consist of two parts: the Fluent API and the Binding class. The Fluent API provides numerous methods on dependent objects, while the Binding class offers static factory methods.

In the following example, two integers are bound so that their values ​​are always automatically added to the sum sum :

package application;

import javafx.beans.property.IntegerProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.binding.NumberBinding;

public class Main {

    public static void main(String[] args) {
        IntegerProperty num1 = new SimpleIntegerProperty(1);
        IntegerProperty num2 = new SimpleIntegerProperty(2);

        NumberBinding sum = num1.add(num2);

        System.out.println(sum.getValue());

        num1.set(2);

        System.out.println(sum.getValue());
    }

}

There are three variables in total, namely the two dependent variables num1and num2and the bond sum. The dependent variables are both of type IntegerPropertyand the bond itself is of type NumberBinding. sumSo the value of changes automatically if num1or num2change.

Declarative GUI descriptions

Basically, graphical interfaces can be set up using a program API, or they can be specified in a declarative description. In the case of declarative interfaces, the arrangement of the components is described in an external resource file.

FXML

In addition to the possibility of building the scene graph using the program code, JavaFX also offers the possibility of configuring the objects using XML . With FXML, JavaFX provides an easy-to-learn, declarative language that allows an alternative definition of graphical interfaces purely via XML. Since XML is structured hierarchically, the basic hierarchical structure of a GUI in containers and components can be mapped very well on an XML basis. This also makes it easier to cleanly separate the layout from the code. In addition, web technologies such as CSS (Cascading Style Sheets), JavaScript, but also other languages ​​such as Groovy can be used there by being embedded in the XML code and linked to it.

The class javafx.fxml.FXMLLoaderand its class method load(...)are used to load an FXML resource . Here the relative path to the *.fxmlfile must be passed as a parameter. Now the specified file can be loaded as a resource and an object of the type javafx.scene.Parentcan be generated from it. This is passed as a parameter to the constructor of the Scene object.

The Java documentation illustrates the difference between code and FXML using the following simple example:

The following program code builds a graphical user interface, which consists of one BorderPanethat contains Labelthe one labeled Page Title at the top and one Labelwith the label Some data here in the center :

BorderPane border = new BorderPane();
Label toppanetext = new Label("Page Title");
border.setTop(toppanetext);
Label centerpanetext = new Label ("Some data here");
border.setCenter(centerpanetext);

The same interface is described in FXML as follows:

<BorderPane>
    <top>
        <Label text="Page Title"/>
    </top>
    <center>
        <Label text="Some data here"/>
    </center>
</BorderPane>

The hierarchical structure of the surface can therefore be represented very well in the hierarchically structured markup language FXML. This makes it easier to add components and build the outline of a GUI.

The Scene Builder

The JavaFX Scene Builder is a graphical tool that simplifies the creation of FXML files. With the tool GUI elements can be designed without programming knowledge. The user can use drag and drop to visually design and generate the XML structures from FXML.

Oracle has stopped development of the tool and released the program's source code under a BSD-like license. As a result, Gluon took over maintenance and commercial support.

FXGraph

FXGraph is a simple DSL ( Domain Specific Language ) for defining the object graph, which is implemented in FXML in the background. FXGraph comes from the e (fx) clipse project, a JavaFX support in Eclipse . FXGraph is more compact than FXML and is vaguely reminiscent of JSON .

criticism

The former Sun employee and Codename One founder Shai Almog certifies that JavaFX will have a rather bright future. He divides JavaFX users into three categories: companies with large investments in Swing, students, and die-hard fans. According to Almog, it is difficult to build a lively community on this foundation . In addition, Oracle does not send out any clear signals as to its future commitment to JavaFX. Overall, he blames three main reasons for the lack of a future for JavaFX:

  • Oracle itself does not use JavaFX or does not use it to a sufficient extent: Even Swing-based products are not moving in the direction of JavaFX. In addition, the Scene Builder has not been distributed by Oracle itself for some time.
  • JavaFX has never gained the same impact as Swing. The main target group of JavaFX, namely the Swing developers, have not switched to the new technology.
  • The job market looks bleak: On the career site dice.com , Almog found only 28 jobs that required JavaFX knowledge, as opposed to 198 job offers for Swing, 2333 for Android and 16752 for Java EE (as of November 22, 2015).

After support for the ARM Embedded Platform and the development of the Scene Builder by Oracle were discontinued, the iJUG association (Association of German Java User Groups) demanded an explicit commitment to JavaFX from Oracle. As a result, Don Smith (Oracle Senior Director Product Management) made it clear that JavaFX would continue to be the recommended technology for the development of rich clients and will be further developed in this regard. The lack of support for the ARM platform has to do with the great effort involved in guaranteeing sustainable commercial ARM support in view of the rapidly changing hardware technology. The Scene Builder has been made available under the open BSD license and the strategy is now to integrate the Scene Builder into tools and development platforms. Smith refers in particular to the startup Gluon, which deals with JavaFX ports and the Scene Builder.

Overall, Java competes with numerous other technologies: on the server side, for example, with Node.js and Ruby on Rails , on the mobile side with iOS and in the mobile and desktop areas with HTML and JavaScript. Time has yet to tell whether JavaFX will prevail as a technology for web interfaces.

Some experts see a niche for JavaFX in particular in the area of ​​powerful desktop clients with sophisticated graphical interaction, in which it could establish itself permanently. You can see the strengths of the framework not least in the development of hybrid desktop applications. Anyone developing a client with direct access to local resources (file system, serial resources, etc.) is in good hands with JavaFX.

literature

  • Anton Epple: JavaFX 8. Basics and advanced techniques. dpunkt.verlag: Heidelberg, 2015.
  • Ralph Steyer: Introduction to JavaFX. Modern GUIs for RIAs and Java applications. Springer Vieweg: Wiesbaden, 2014.
  • Christian Ullenboom: Java is also an island. Introduction, training, practice. 11th edition, Galileo Press: Bonn, 2014, especially pp. 1009-1063.
  • Christian Ullenboom: Java SE 8 standard library. The Java Developer's Guide. 2nd edition, 2014, Galileo Press: Bonn, 2014, especially pp. 1031-1076.

Web links

References and comments

  1. Ullenboom: Java is also an island. 11th edition, 2014, p. 1011.
  2. JavaFX FAQ . Retrieved Feb. 29, 2016.
  3. ^ The Future of JavaFX and Other Java Client Roadmap Updates . Retrieved Nov. 17, 2018.
  4. a b c Ullenboom: Java is also an island. 11th edition, 2014, p. 1011.
  5. JavaFX 1.0 is live ( Memento of the original dated December 7, 2008 in the Internet Archive ) Info: The archive link was inserted automatically and not yet checked. Please check the original and archive link according to the instructions and then remove this notice.  @1@ 2Template: Webachiv / IABot / blogs.sun.com
  6. JavaFX 1.3 release ( Memento from April 30, 2011 in the Internet Archive )
  7. javafx.com ( Memento of the original from October 29, 2010 in the Internet Archive ) Info: The archive link was inserted automatically and has not yet been checked. Please check the original and archive link according to the instructions and then remove this notice.  @1@ 2Template: Webachiv / IABot / javafx.com
  8. Innovations in JavaFX 2.0 . Netzwelt , accessed October 13, 2011
  9. a b Ullenboom: Java is also an island. 11th edition, 2014, p. 1012.
  10. Hendrik Ebbers: JavaFX8 - What's new? In: jaxenter (created March 20, 2014, accessed December 12, 2016).
  11. JDK for ARM 8u33 release notes . Oracle . February 16, 2013. Retrieved on February 29, 2016: “ Starting with JDK 8u33, JavaFX Embedded is removed from the ARM bundle and is not supported. "
  12. ^ Oracle Corporation: Java Client Roadmap Update. Oracle Copration, March 2018, accessed March 20, 2018 .
  13. ^ Steyer: Introduction to JavaFX. 2014, pp. 166–167.
  14. Oracle: JavaFX Architecture In: http://docs.oracle.com (last changed 2013, accessed December 14, 2016)
  15. Note: Not to be confused with the secret service software PRISM
  16. a b c Steyer: Introduction to JavaFX. 2014, p. 8.
  17. Gerrit Grunwald: Visualization in Java with JavaFX In: heise Developer (created on June 28, 2013, accessed on December 14, 2016).
  18. ^ Steyer: Introduction to JavaFX. 2014, pp. 8–9.
  19. Note: The main () method is basically not necessary for a JavaFX application, while it is the central entry point for a normal Java application. It is only generated by NetBeans for security reasons, in order to guarantee the start of the application in the event of insufficient JavaFX support on target platforms. Netbeans itself ignores the main () method. See Steyer: Introduction to JavaFX. 2014, p. 29.
  20. Ullenboom: Java SE 8 standard library. 2nd edition 2014, p. 1032.
  21. Oracle: javafx.application - Class Application on docs.oracle.com (accessed December 11, 2016); Epple: JavaFX 8. 2015, pp. 9-10.
  22. Note : The reason for this is that the init method - just like the class constructor - is still called by the application's launcher thread. UI elements can only be created and modified in the JavaFX application thread. See Epple: JavaFX 8. 2015, p. 10.
  23. a b Steyer: Introduction to JavaFX. 2014, p. 29.
  24. Epple: JavaFX 8. 2015, p. 11.
  25. For a detailed description of the Stage class, see Oracle: Class Stage on docs.oracle.com (accessed December 11, 2016). See also Epple: JavaFX 8. 2015, pp. 11–13.
  26. ^ Steyer: Introduction to JavaFX. 2014, pp. 29, 65.
  27. Epple: JavaFX 8. 2015, p. 13.
  28. Oracle: Class Scene on docs.oracle.com (accessed December 11, 2016).
  29. Ullenboom: Java SE 8 standard library. 2nd edition, 2014, p. 1033.
  30. ^ Oracle: Class Group on docs.oracle.com (accessed December 11, 2016); Ullenboom: Java SE 8 standard library. 2nd edition, 2014, pp. 1034-1035.
  31. Oracle: Class Control on docs.oracle.com (accessed December 11, 2016); Ullenboom: Java SE 8 standard library. 2nd edition, 2014, p. 1034.
  32. Ullenboom: Java SE 8 standard library. 2nd edition, 2014, p. 1036.
  33. Epple: JavaFX 8 2015, pp. 43-44; Oracle: Using JavaFX UI Controls on docs.oracle.com (accessed December 11, 2016)
  34. Jeff Friesen: Exploring JavaFX's Application class In: JavaWorld (created April 14, 2016, accessed December 13, 2016).
  35. ^ Steyer: Introduction to JavaFX. 2014, p. 201.
  36. Note: In contrast to this, console-based or older graphic programs are often a linear or deterministic sequence of instructions and / or inputs that are processed one after the other.
  37. ^ Steyer: Introduction to JavaFX. 2014, p. 201.
  38. ^ Steyer: Introduction to JavaFX. 2014, p. 201.
  39. ^ Steyer: Introduction to JavaFX. 2014, pp. 202–205.
  40. ^ Steyer: Introduction to JavaFX. 2014, pp. 205-209.
  41. a b Ullenboom: Java SE 8th standard library. 2nd edition, 2014, p. 1037.
  42. ^ Steyer: Introduction to JavaFX. 2014, pp. 193-195; Ullenboom: Java SE 8 standard library. 2nd edition 2014, pp. 379–388; Epple: JavaFX 8. 2015, pp. 22-23.
  43. Martin Gerlach: Java SE 8 Innovations (Part 1): Lambda expressions and default methods In: Neo Tech Blog (created on November 17, 2014, accessed on December 16, 2016).
  44. Ullenboom: Java SE 8 standard library. 2nd edition 2014, p. 63.
  45. java beginners: What are lambda expressions? In: https://javabeginners.de (last change on July 3, 2016, accessed on December 16, 2016); Marco Jakob: JavaFX 8 Event Handling Examples In: code.makery - Learning how to code (created on May 3, 2014; accessed on December 16, 2016).
  46. a b Steyer: Introduction to JavaFX. 2014, p. 225.
  47. a b c d Oracle: JavaFX: Properties and Binding Tutorial In: docs.oracle.com (accessed December 13, 2016).
  48. Ullenboom: Java SE 8 standard library. 2nd edition 2014, pp. 806–807.
  49. ^ Steyer: Introduction to JavaFX. 2014, pp. 228-231.
  50. Note: This is comparable to XAML (Extensible Application Markup Language) from Microsoft's .NET framework.
  51. ^ Steyer: Introduction to JavaFX. 2014, pp. 9-10; Ullenboom: Java SE 8 standard library. 2nd edition 2014, pp. 1062-1063; Ullenboom: Java is also an island. 11th edition, 2014, pp. 1013-1014.
  52. ^ Steyer: Introduction to JavaFX. 2014, pp. 65–66.
  53. Oracle: Mastering FXML In: http://docs.oracle.com (Update 2014, accessed December 14, 2016).
  54. The tool is available at the following URL for Windows, OS X and Linux: http://gluonhq.com/labs/scene-builder/
  55. Simon Vienot: openjfx-dev mailing list. "Scene Builder is now open source!" . 3 Dec 2013. Retrieved 29 Mar. 2016.
  56. ^ Gluon supports Scene Builder . 4th Mar 2015. Accessed 29 Mar. 2016.
  57. Tom Schindl: FXGraph In: https://www.eclipse.org/ (last changed on December 9, 2013; accessed on December 13, 2016).
  58. Ullenboom: Java is also an island. 11th edition, 2014, p. 1014.
  59. a b Shai Almog: Should Oracle Spring Clean JavaFX? In: DZone (created November 22, 2015, accessed December 14, 2016); see also Michael Thomas: rest in peace, JavaFX? In: JAXenter (created November 24, 2015, accessed December 14, 2016).
  60. iJUG: iJUG demands a clear commitment to JavaFX from Oracle ( memento of the original from September 23, 2016 in the Internet Archive ) Info: The archive link was automatically inserted and not yet checked. Please check the original and archive link according to the instructions and then remove this notice. In: iJUG (created on January 27, 2016; update February 2, 2016; accessed on December 14, 2016) @1@ 2Template: Webachiv / IABot / www.ijug.eu
  61. a b Hartmut Schlosser: Hard but fair: What future does JavaFX have? In: JAXenter (created March 22, 2016, accessed December 14, 2016).
  62. JAXenter, Interview with Alexander Casall: "Only Chuck Norris can do hybrid desktop applications" In: JAXenter (created on April 21, 2015, accessed on December 14, 2016).