I have recently been learning JavaFX 8 by developing a JavaFX application. One of the new concepts in JavaFX is that of properties and binding, whereby, you can link (or bind) the property from one object, to the property of another. In this article, I won’t explain the concepts of binding, or of properties (see Using JavaFX Properties and Binding for more info), but will show you a JavaFX binding example, of how to use binding, to easily set whether a UI control is enabled or disabled, based on a property of another control.
Example 1
Often, when creating a User Interface, one control, needs to be enabled, or disabled, based on another control. One example I had recently, is where I have a ComboBox, with a list of values that the user can choose from, and beside it, a CheckBox, which when checked, will cause the UI to use the default value. The UI logic is, that if the CheckBox is checked, the ComboBox should be disabled, and if the CheckBox is un-checked, the ComboBox should be enabled (see screen shot).
Traditionally I would have had to create a Listener on the CheckBox, and when the state of the CheckBox changed, I would check the new state of the CheckBox and then set the ComboxBox to either enabled or disabled, accordingly.
Use binding, however, I can bind the ComboBox’s disable property, to the CheckBox’s selected property, in one statement:
ComboxBox timeZoneComboBox;
CheckBox useDefaultTimeZoneCheckBox;
...
this.timeZoneComboBox.disableProperty().bind(this.useDefaultTimeZoneCheckBox.selectedProperty());
...
Typically, this would be done in the initialize() method of the ViewController.
Example 2
Another case I had, was where I had a TableView, with Add and Remove buttons. The user could click the Add button to add a row to the table, and the Remove button to remove a row. For the UI logic, I only wanted to Remove button to be enabled, if a row in the Table was currently selected. I was able to do this, with a slightly more complex use of binding:
Button removeButton;
TableView timeZoneTable;
...
this.removeButton.disableProperty().bind(BooleanExpression.booleanExpression(this.timeZoneTable.getSelectionModel().selectedItemProperty().isNull()));
...
In this example, I used binding to bind the Button’s disable property to a booleanExpression based the Table’s SelectionModel’s selectedItem property, by checking if it was null .
These are just two examples of how to use binding to set whether a control is enabled or disabled automatically, based on another control. Hopefully you find these examples useful, and can incorporate this idea into your own JavaFX applications.
I am Victor Ewert, an Independent Software Developer and owner of Ewert Technologies. In the past I have worked as a Software Tester including working on Software Test automation.
My current technology interests include Java, JavaFX, Kotlin, Swift, Privacy and Security, and Mobile App development.
These are very useful,thanks