Skip to content

Binding

Edvin Syse edited this page Feb 9, 2018 · 7 revisions

WikiDocumentationBinding

Binding UI controls to JavaFX Properties

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.

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 express the same:

// 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 unidirectionally, 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(chosen)

// With binding support
checkbox.bind(chosen)

Conversion

Whenever possible, conversion is performed automatically by inspecting the given property type and compare it to the value type of the component. If a converter can be found, it is automatically applied. You can of course override the converter as well:

// Bind age to textfield, custom converter
textfield.bind(age, converter = myCustomConverter)

The converter parameter accepts normal javax.util.StringConverter instances.

Next: Logging