JavaFX API Properties

By Doug Lowe

A powerful feature of JavaFX is its properties. Simply put, a JavaFX property is an observable value that’s exposed by a class. Properties are observable in the sense that you can attach listeners to them. These listeners can be invoked whenever the value of the property changes or becomes unknown.

One of the best features of properties is that you can bind to them, or connect properties together so that when one property changes, the other property is adjusted automatically. In other words, binding allows two properties to be synchronized. When one property changes, the other property changes as well.

All the JavaFX API classes make extensive use of properties. In fact, just about every API get or set method is actually a property getter or setter, and has a corresponding method that returns the property itself.

For example, consider the TextField class, which has methods named getText and setText that get and set the text contained in the text field. These methods are actually getters and setters for a property named text, and the TextField class has a method named textProperty that provides direct access to the text property.

Likewise with the HBox class: It has properties named alignment, hgrow, padding, and spacing which correspond to the getAlignment, setAlignment, getHgrow, setHgrow, getPadding, setPadding, getSpacing, and setSpacing methods.

When you first learn programming, you probably have no need to access the properties directly, so you’ve relied on the getter and setter methods to manipulate the property values. Later, when you discover how to bind property values, you see that accessing these properties can be very useful.

It’s good to learn how to create your own JavaFX properties. Even if you never create JavaFX properties for your own classes, knowing how to do so will help you understand the benefits of working with the properties that are defined as part of the standard JavaFX API classes.