Skip to main content

Observables, Bindings and Listeners

Observables and their related classes are the core of the Reactive aspect of JavaFX, and it’s critical to understand how they work if you want to take advantage of the benefits of Reactive design.

Observable Objects

1 min

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

1 min

ChangeListeners are way to manually monitor a Property for changes in its value, and then to trigger some code when a change happens.

90%+ of the functionality that you need to build in a Reactive application can be achieved via Bindings, which allow the “State” of your application to be share back and forth with the Nodes that make up your GUI. But, sometimes you need an “Action” to take place in response to some change in your Presentation Model, or in one of the Properties inside a screen Node. In those cases you’ll need to use a Listener to listen for the change to take place and trigger your code.