Проект

Общее

Профиль

Property

One-directional binding

When you invoke the bind() method on a target property, you pass it a second property as an argument – the binding source.

StringProperty sourceProperty = new SimpleStringProperty("First Value");
StringProperty targetProperty = new SimpleStringProperty("Second Value");
targetProperty.bind(sourceProperty);

Under the bonnet, the target stores a reference to the new source property and listens for changes. When the source value changes, it automatically updates the target (itself) when a change is detected.
SimplePropertyBinding

In this case, targetProperty will track the value of sourceProperty. A few notes on extra bits for this method:

  • If the property is currently bound, the current binding is deleted and the new one replaces it
  • If a null argument is provided, the method throws a NullPointerExeption
  • The method immediately copies the value of the property it’s listening to, so the current value of the target property is lost.

Two-directional binding

It is, of course, possible to wire the properties together in both directions, linking their values together so that their values are always the same. To accomplish this, we invoke bindBidirectional(), passing the source property as an argument again.

StringProperty sourceProperty = new SimpleStringProperty("First Value");
StringProperty targetProperty = new SimpleStringProperty("Second Value");
targetProperty.bindBidirectional(sourceProperty);

If the values of the properties are different, then the order of the method call is important in determining the start value for the binding.

The method applied to targetProperty immediately updates the value of targetProperty before sourceProperty is bound reciprocally. That means that after a bidirectional binding, both properties will have the value of the property passed as an argument (the source property).

SimplePropertyBidirectionalBinding

In addition to the basic binding, which is limited to a carbon-copy approach, JavaFX supports more complex binding: creating multiple or complex manipulations of one property to update another.

If binding one property to another doesn’t cover your use case, don’t worry – I’ll go through more complex bindings in the following sections.