本文介绍了在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());

这篇关于在JavaFX中启用/禁用按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-27 02:17