Properties and Binding
Java 8 introduced the concept of properties for objects. Some programming languages support properties natively such as .Net but in Java they are added as part of the standard library. Properties encapsulate class fields to provide high level access to them via change listeners and direct coupling of properties.
A standard use case for properties is binding two properties together to automatically update one property when the other one changes its value.
Property example
The example below describes the steps you take in Java to define a String property called "name:"
- Create a StringProperty object and instantiate it. Here we use a SimpleStringProperty as the actual object. The alternative would be the ReadOnlyStringProperty.
- Create a getter for the value.
- Create a setter for the value.
- Create a function that retrieves the property object.
public class Person {
private StringProperty name = new SimpleStringProperty();
public String getName() {
return name.get();
}
public void setName(String value) {
name.set(value);
}
public StringProperty nameProperty() {
return name;
}
}
Bindings
Java distinguishes two types of property bindings: low level and high level bindings.
Properties in JavaFX
Many UI elements of JavaFX use properties instead of plain fields. This enables
you to easily bind your own properties to these controls. The TextField
for
example provides a property for its text-value. You can bind the name
property of a person
instance to this to automatically set the value of the
person's name to the text value of the TextField.
public void initialize(URL url, ResourceBundle resources) {
textField.textProperty().bind(person.nameProperty);
}
But note that using bind()
only creates a one way binding. Changing the
value of the name property on a person instance does not update the value of the
TextField. If you wish it to do so just use bindBidrectional()
instead of
bind()
and both properties will always have the same value, no matter which
one is edited.