Sunday, December 11, 2016

Day 11, Java Holiday Calendar 2016, Try JavaFX

11. Building Reactive Systems with JavaFX

Today's tips is to take the leap from Swing to JavaFX, the latter being much more modern and feature full than the former. 

The open-source Speedment UI tool is built using JavaFX, allowing the tool to be more reactive, in the sense that if we change something in a text box, for example, that property can affect other components directly and dynamically. E.g. if we change the name of a schema, then a tree component showing the entire database structure is updated in real time and perhaps also a connection URL that depends on the schema name. Here is the complete UI tool code written using JavaFX.

Properties and Observability

Property objects are important when designing JavaFX applications. Almost everything in the FX library can be observed such as the text content of a field, the position of a slider or the status of a checkbox. Properties can be Writable and Readable. A writable value can be updated using its setter or by user interaction with the component whereas a readable can react (via notifications) to external events.

Here is how it looks like:

// Both readable and writable
StringProperty name = new SimpleStringProperty("Schema Name"); 

// Only readable
ObservableBooleanValue nameIsEmpty = name.isEmpty();

So, the variable nameIsEmpty can return true if the name is currently empty or false if name is non-empty.


Now that we have writable and readable values, we can define custom rules how they all relate to each other (e.g. we can "wire up" our model). Bindings are either unidirectional or bidirectional. Unsurprisingly, bidirectional bindings requires that both properties are writable.

Here is an example of binding:

TextField firstField  = new TextField("first");
TextField secondField = new TextField("second");

This will hint JavaFX that we want our firstTextField to have the same width that the secondField. This relation will be maintained over time so if we change the secondField's width, then the firstField's hinted width is updated automatically.


JavaFX can be combined with other reactive libraries such as ReactFX and RxJavaFX to create even more powerful applications.

Read more on JavaFX on DZone here and here (Refcardz).

Follow the Java Holiday Calendar 2016 with small tips and tricks all the way through the winter holiday season.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.