Search code examples
javafxproperty-binding

JavaFX: check whether a text property is blank (and not just empty)


I want to have a button enabled or disabled based on whether a text field contains anything, and I want to implement this by using property binding.

So at first I used the isEmpty() method on the text field's text property to create a boolean binding for the button's disabled property:

startSearchButton.disableProperty().bind(searchField.textProperty().isEmpty());

While the binding works, my definition of "text field contains anything" is different to what the isEmpty() method does, namely just checking if the text's length is > 0. However, I'm interested in whether there is "real" text, i.e. whether the text field is blank (not just not empty, but actually not only whitespace).

Unfortunately there is no method isBlank(), and I also couldn't find anything appropriate in the Bindings utility class. Now I saw that you can implement any custom boolean property you like via the Bindings.createBooleanProperty method, but I'm not yet familiar with the concept of defining custom bindings. How would I have to implement such a boolean property for my case?


Solution

  • You can create a custom binding using (among many methods) Bindings.createBooleanBinding(...). The first argument is a function that computes the value of the binding (you can trim whitespace from the text with trim() and then check if the result is empty); the remaining arguments are a list of observables that trigger recomputation of the binding. You want to recompute the binding when the text in the text field changes, so just specify the text property:

    startSearchButton.disableProperty().bind(Bindings.createBooleanBinding(() -> 
        searchField.getText().trim().isEmpty(),
        searchField.textProperty());