Roger
Roger

Reputation: 597

How to bind 2 textfields and at least 1 out of 3 checkboxes to a button

Right now I have this button which I want to enable once 2 textfields have been filled out and at least 1 out of 3 checkboxes are checked. This is what I have so far but it doesn't seem to work the way it's suppose to. I would greatly appreciate any of your inputs. Thank you in advance.

button.disableProperty().bind(
   Bindings.isEmpty(textField1.textProperty())
   .or(Bindings.isEmpty(textField2.textProperty()))
   .or(checkBox1.selectedProperty())
   .or(checkBox2.selectedProperty())
   .or(checkBox3.selectedProperty())
);  

Upvotes: 0

Views: 53

Answers (2)

fabian
fabian

Reputation: 82451

I'm not a huge fan of chaining or, and and not to create an expression for one simple reason. The actual expression isn't easy to read. Bindings.createBooleanBinding results in code that is much easier to read:

button.disableProperty().bind(Bindings.createBooleanBinding(
    () -> {
        if (textField1.getText().isEmpty() || textField2.getText().isEmpty()) {
            return true;
        }
        return !(checkBox1.isSelected() || checkBox2.isSelected() || checkBox3.isSelected());
    },
    textField1.textProperty(), textField1.textProperty(), checkBox1.selectedProperty(), checkBox2.selectedProperty(), checkBox3.selectedProperty()
));

If you insist on chainging and, or and not, you should create the following expression:

(e1 || e2 || !(s1 || s2 || s3))

where e1 and e2 stand for empty text fields and s1, s2, s3 for selected checkboxes

button.disableProperty().bind(
    textField1.textProperty().isEmpty()
           .or(textField2.textProperty().isEmpty())
           .or(
               checkBox1.selectedProperty()
                        .or(checkBox2.selectedProperty())
                        .or(checkBox3.selectedProperty()).not())
);  

Upvotes: 2

Roger
Roger

Reputation: 597

Ok, I actually tried the solution listed below. It seems to work in that it needs to fill out 2 textfields and check at least 1 out of 3 checkboxes.

button.disableProperty().bind(
   Bindings.isEmpty(textField1.textProperty())
   .and(Bindings.isEmpty(textField2.textProperty()))
   .or(checkBox1.selectedProperty().not())
   .and(checkBox2.selectedProperty().not())
   .and(checkBox3.selectedProperty().not())
); 

Upvotes: 0

Related Questions