JavaFX bind to multiple properties


Question

I have a simple fxml with a textfield and a button. I'd like to have the button disabled if the textfield is empty. So I insert something like the following in my controller:

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

..and that works fine. The problem is when I add a second textfield and would like my button to be disabled if either textfield is empty. What to do then? I tried the following, but that doesn't work:

@Override
public void initialize(URL url, ResourceBundle bundle) {
  button.disableProperty().bind(textField.textProperty().isEqualTo(""));
  button.disableProperty().bind(textField2.textProperty().isEqualTo(""));
}
1
14
11/28/2013 11:08:23 AM

Accepted Answer

This is possible by binding to a boolean expression via Bindings:

button.disableProperty().bind(
    Bindings.and(
        textField.textProperty().isEqualTo(""),
        textField2.textProperty().isEqualTo("")));
20
11/28/2013 11:21:31 AM

In addition to Andreys approach, I found that you can also do it like this:

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

    button.disableProperty().bind(booleanBinding);

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon