【问题标题】:Enabling/Disabling buttons in JavaFX [duplicate]JavaFX中的启用/禁用按钮[重复]
【发布时间】:2015-06-20 20:53:30
【问题描述】:

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

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

有没有更简单的方法来做到这一点?另外,如果我在这些区域中添加文本,按钮是否应该重新启用其自身?

【问题讨论】:

  • 该代码应该可以工作。如果(任何文本框为空为空){禁用按钮},您的逻辑会执行您希望它执行的操作。这有点乱,但它有效。

标签: java javafx


【解决方案1】:

使用文本字段的textProperty() 创建一个BooleanBinding,然后将其与按钮的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());

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

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

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

只需将and 替换为or

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

【讨论】:

  • bind property to properties of every element in observable Collection 的答案中有一些有趣的解决方案可以将多个布尔属性与多个布尔属性相结合,尽管这些答案对于原始发布者试图实现的目标来说可能是多余的。
  • 好吧,这有点工作,当我从...切换时怎么会...
  • .add to .or 它应该正常工作。另外为什么只需要2个文本字段。多个文本字段会在 netbeans 中给我一个错误。
  • @user3505212 编辑了我的答案。
  • @ItachiUchihaok 只是让你知道。或者为我工作。不是和。谢谢
【解决方案2】:

在摇摆中,我们可以禁用一个按钮,如下所示: JButton start = new JButton("Start"); start.setEnabled(false);

但是在javaFX中这个函数(setEnabled)变成了setDisabled,所以我们可以在javaFX中使用这个代码: start.setDisable(false);

【讨论】:

  • 注意措辞:setDisabled() 是受保护的方法而不是公共方法,并且与公共setDisable() 方法具有不同的含义。问题发布者已经为他的用例使用了正确的方法=> setDisable()
  • 仅供参考,此答案中的代码 sn-p 似乎已更正为setDisable(...),但它使用的句子仍为“setDisabled”。
猜你喜欢
  • 2014-09-27
  • 2018-07-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-26
  • 2012-09-20
  • 2021-08-03
相关资源
最近更新 更多