JavaFX绑定到多个属性

mar*_*_dk 14 java binding javafx

我有一个带文本字段和按钮的简单fxml.如果textfield为空,我想禁用该按钮.所以我在我的控制器中插入如下内容:

@Override
public void initialize(URL url, ResourceBundle bundle) {
  button.disableProperty().bind(textField.textProperty().isEqualTo(""));
}
Run Code Online (Sandbox Code Playgroud)

..并且工作正常.问题是当我添加第二个文本字段并希望如果任一文本字段为空时我的按钮被禁用.该怎么办?我尝试了以下,但这不起作用:

@Override
public void initialize(URL url, ResourceBundle bundle) {
  button.disableProperty().bind(textField.textProperty().isEqualTo(""));
  button.disableProperty().bind(textField2.textProperty().isEqualTo(""));
}
Run Code Online (Sandbox Code Playgroud)

And*_*hev 20

这可以通过以下方式绑定到布尔表达式Bindings:

button.disableProperty().bind(
    Bindings.and(
        textField.textProperty().isEqualTo(""),
        textField2.textProperty().isEqualTo("")));
Run Code Online (Sandbox Code Playgroud)

  • .textProperty().isEmpty() - 对我来说似乎是一种更好的方法. (2认同)

mar*_*_dk 7

除了Andreys的方法,我发现你也可以这样做:

    BooleanBinding booleanBinding = 
      textField.textProperty().isEqualTo("").or(
        textField2.textProperty().isEqualTo(""));

    button.disableProperty().bind(booleanBinding);
Run Code Online (Sandbox Code Playgroud)