Featured Post

Applying Email Validation to a JavaFX TextField Using Binding

This example uses the same controller as in a previous post but adds a use case to support email validation.  A Commons Validator object is ...

Sunday, January 10, 2016

JavaFX TextField Contents Binding Example

JavaFX binding is a powerful way to keep your UI in sync with itself without requiring bulky ChangeListeners.  Binding lets you declare an association between exposed properties of JavaFX components.  Moreover, expressions can be applied to allow for binding properties of different types. This example demonstrates binding the String-based textProperty of a TextField to the Boolean-based disableProperty of a Button.

App Showing a Bound Add Button and Filter TextField


This video shows a TableView add operation and a filter operation.  The + Button adds rows to the TableView.  The Filter TextField restricts the rows presented to the user.


In the video, adding text to the TextField -- in advance of executing the filter -- will disable the Button.  This is because my add operation is producing a template row that will likely be filtered by the criteria.  Rather than have the add operation appear to have no effect, I coerce the user into removing the filter.

btnAdd is the + Button and tfFilter is the filter TextField.  To link them, I add the following line in my @FXML initialize() method.

        btnAdd.disableProperty().bind( tfFilter.textProperty().isNotEmpty());

If you're coming from a Swing background, JavaFX binding is a new and powerful concept.  Simple declarative statements replace Listeners as a way to link UI components together.  The rich set of methods available to JavaFX properties allows for complex expressions.  In this example, I bound the String contents of a TextField to the on/off disable switch of a Button, removing the need for me to unpack, interrogate, and set the properties by hand in a Listener.

No comments:

Post a Comment