JavaFX binding example to sync a Control’s disabled state

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).

ComboBox Binding Example

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:

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:

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.

The following two tabs change content below.

Victor Ewert

Proprietor/Developer at Ewert Technologies
I am Victor Ewert, a 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, Swift, Privacy and Security, and Mobile App development.

1 thought on “JavaFX binding example to sync a Control’s disabled state

Leave a comment