如何在特定条件下禁用按钮?例如,我有许多文本字段和按钮,当这些文本字段为空时,我的按钮之一应该被禁用。我已经有了这个代码。
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);
}
有没有更简单的方法来做到这一点?另外,如果我在这些区域添加文本,按钮是否应该重新启用它自己?
使用文本字段的 textProperty()
创建一个 BooleanBinding
,然后将其与 Button 的 disableProperty()
绑定(bind)。
用于在任何文本字段不为空时启用按钮。
// 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());
或者,更好的方法是直接在属性上使用和
:
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());