Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaFX bind to multiple properties

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(""));
}
like image 273
martin_dk Avatar asked Nov 28 '13 11:11

martin_dk


3 Answers

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

button.disableProperty().bind(
    Bindings.and(
        textField.textProperty().isEqualTo(""),
        textField2.textProperty().isEqualTo("")));
like image 179
Andrey Chaschev Avatar answered Nov 07 '22 21:11

Andrey Chaschev


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);
like image 45
martin_dk Avatar answered Nov 07 '22 20:11

martin_dk


In addition to martin_dk answer, if you want to bind more than two properties you will get code like below, looks weird, but it works.

BooleanBinding booleanBinding
        = finalEditor.selectedProperty().or(
                staticEditor.selectedProperty().or(
                        syncEditor.selectedProperty().or(
                                nativeEditor.selectedProperty().or(
                                        strictEditor.selectedProperty()))));

abstractEditor.disableProperty ().bind(booleanBinding);
like image 4
Korvin Gump Avatar answered Nov 07 '22 20:11

Korvin Gump