在JavaFX中启用/禁用按钮

use*_*212 4 java javafx

如何在一定条件下禁用按钮?例如,我有许多文本字段和按钮,当这些文本字段为空时,应禁用其中一个按钮.我已经有了这个代码.

if(txtID.getText().isEmpty()&&txtG.getText().isEmpty()
            &&txtBP.getText().isEmpty()&&txtD.getText().isEmpty()
            &&txtSP.getText().isEmpty()&&txtCons.getText().isEmpty()){
       btnAdd.setDisable(true);
       }
else{
btnAdd.setDisable(false);
}
Run Code Online (Sandbox Code Playgroud)

有更简单的方法吗?此外,如果我在这些区域添加文本,按钮是否应重新启用它自己?

Ita*_*iha 13

BooleanBinding使用文本字段创建一个textProperty(),然后将其与Button的绑定disableProperty().

如果任何文本字段不为空,则启用按钮.

// I have added 2 textFields, you can add more...
BooleanBinding booleanBind = Bindings.and(text1.textProperty().isEmpty(),
                                              text2.textProperty().isEmpty());
button.disableProperty().bind(booleanBind);
Run Code Online (Sandbox Code Playgroud)

超过2个文本字段

BooleanBinding booleanBind = Bindings.and(text1.textProperty().isEmpty(),
          text2.textProperty().isEmpty()).and(text3.textProperty().isEmpty());
Run Code Online (Sandbox Code Playgroud)

或者,更好的方法是and直接在属性上使用:

BooleanBinding booleanBind = text1.textProperty().isEmpty()
                            .and(text2.textProperty().isEmpty())
                                      .and(text3.textProperty().isEmpty());
Run Code Online (Sandbox Code Playgroud)

仅在所有文本字段都有文本时启用按钮.

只需更换andor.

BooleanBinding booleanBind = text1.textProperty().isEmpty()
                            .or(text2.textProperty().isEmpty())
                                      .or(text3.textProperty().isEmpty());
Run Code Online (Sandbox Code Playgroud)