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

南笙酒味 提交于 2019-12-06 00:43:06

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

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