在JavaFX中启用/禁用按钮

问题描述:

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

how do you disable buttons under a certain condition? For example, i have many text fields and buttons, when those text fields are empty one of my buttons should be disabled. i already have this code.

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

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

is there an easier way to do this? Also if i add text into those areas shouldnt the button be re enable its self?

使用textfield的创建 BooleanBinding textProperty()然后用Button的 disableProperty()绑定它。

Create a BooleanBinding using the textfield's textProperty() and then bind it with the Button's disableProperty().

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

超过2个文本字段

BooleanBinding booleanBind = Bindings.and(text1.textProperty().isEmpty(),
          text2.textProperty().isEmpty()).and(text3.textProperty().isEmpty());

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

Or, a better approach is to use and directly on the property:

BooleanBinding booleanBind = text1.textProperty().isEmpty()
                            .and(text2.textProperty().isEmpty())
                                      .and(text3.textProperty().isEmpty());



仅当所有文本字段都有文本时启用按钮。



只需用替换

BooleanBinding booleanBind = text1.textProperty().isEmpty()
                            .or(text2.textProperty().isEmpty())
                                      .or(text3.textProperty().isEmpty());