-
Notifications
You must be signed in to change notification settings - Fork 271
Binding
Wiki ▸ Documentation ▸ Binding
Most JavaFX UI Controls have one property that represents the value of the component. The syntax for binding is a bit verbose, so TornadoFX provides a means to reduce the binding boilerplate considerably.
Consider this example, which uses plain JavaFX binding with no help from TornadoFX:
val name = SimpleStringProperty()
val age = SimpleDoubleProperty(42.0)
// Bind name readwrite to textfield
textfield.textProperty().bindBidirectional(name)
// Bind name readonly to textfield
textfield.textProperty().bind(name)
// Bind age to textfield
textfield.textProperty().bindBidirectional(age, NumberStringConverter())
Now let's use the extensions TornadoFX provides to bind the property that represents the value in the ui control to our model's property:
// Bind name readwrite to textfield
textfield.bind(name)
// Bind name readonly to textfield
textfield.bind(name, true)
// Bind age to textfield, converter extracted from type of 'age'
textfield.bind(age)
As you can see, bind
means bindBidirectional
, which is the opposite of what JavaFX does by default. This might seem strange, but the value property for a UI component is bound read write much more often than every other property on a component, so it reduces noise. To bind unidirectional, add readonly = true
or simply true
as the second parameter.
You no longer need to keep track of what property inside the control is representing the value. Consider CheckBox:
val chosen = SimpleBooleanProperty()
// Without binding support
checkbox.selectedProperty().bindBidirectional(chose)
// With binding support
checkbox.bind(chosen)
You can add a converter to the binding as well:
// Bind age to textfield, custom converter
textfield.bind(age, converter = myCustomConverter)
The converter
parameter accepts normal javax.util.StringConverter
instances.
Next: Logging