↓ Skip to main content

Observables, Bindings and Listeners

Most Reactive frameworks work by holding a data representation of the “State” of the GUI in some kind of structure, then monitoring that structure for changes and updating the GUI whenever they occur. Conversely, the GUI itself may update the “State” in response to actions by the user.

In JavaFX, the work of connecting the GUI to your “State” is done via an extensive library of “Observable” objects, along with classes designed to allow you to link “Observable” objects together. Virtually every configurable element of every screen component is implemented as Observable objects, which means that you can easily connect them directly to your data representation of “State”.

These libraries are huge, and that means that it takes some time to learn about them. However, you can start out doing some simple things right away, and then learn more advanced techniques as you go along.

Finally, every application eventually needs actions. JavaFX has a library of classes designed to capture and handle actions, called Events. It also has classes called Listeners that allow you to turn changes in “State” into actions.

Observable Objects

2 mins

The absolute core element of observability in JavaFX is the Property and it’s related sub-classes and interfaces. Properties are used for virtually every aspect of every screen Node that you can interact with. Values in TextFields and Labels are stored in a StringProperty, while elements like maxWidth and minWidth are stored in DoubleProperties. The items in a ListView or a TableView are stored in an ObservableList.

The key to creating Reactive applications in JavaFX is to use these Properties as observables, and not simply annoying wrappers around their values. Create Bindings to link them together instead of stuffing values in them and scraping values out them.

But to do that, you need to understand they work, and how to use them properly.

Bindings

·1 min

If you look at the JavaDocs for the interface, Property you’ll find that all of its methods are only concerned with binding. That’s how important Bindings are to JavaFX.

Binding is a class, but it’s also an action. Bindings are how you connect two or more Properties together, so that you can have actual data stored inside a single place - a Property - and use it all over your application without having to write code to update all those places whenever it changes.

Since the JavaFX screen Nodes are just chock full of Properties, this means that it’s easy to connect and control your GUI from Properties that you create in your Presentation Model.

Listeners and Events

1 min
In Reactive design there are two different and distinct elements that add to the dynamic feel of the GUI. The first is the “State” and changes to the “State”. The second is “Events” and their associated actions. In this section we talk about the second of those, the “Events”, and how to transform changes to “State” into actions.