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

喜你入骨 提交于 2019-12-22 10:08:24

问题


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?


回答1:


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());



回答2:


You can do this too:

  1. With Apache StringUtils.isBlank()

    startSearchButton.disableProperty().bind(Bindings.createBooleanBinding(() -> 
        StringUtils.isBlank(searchField.getText()),
        searchField.textProperty());
    
  2. Create you own method

    public static boolean IsNullOrWhitespace(String s) {
            if(s == null) {
                return true;
            }
    
            for(int i = 0; i < s.length(); ++i) {
                if(!Character.isWhitespace(s.charAt(i))) {
                    return false;
                }
    
            }
            return true;
        }
    

and then:

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


来源:https://stackoverflow.com/questions/35948307/javafx-check-whether-a-text-property-is-blank-and-not-just-empty

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!