Disabling Button while TextFields empty not workin

2019-09-01 01:10发布

问题:

BooleanBinding bb = new BooleanBinding() {
    {
       super.bind(addnum.textProperty(),addt1.textProperty(),addt2.textProperty(),
               addt3.textProperty(),addasg.textProperty(),addatt.textProperty());
    }
    @Override
    protected boolean computeValue() {
      return (addnum.getText().isEmpty() && addt1.getText().isEmpty()
            && addt2.getText().isEmpty() && addt3.getText().isEmpty()
            && addasg.getText().isEmpty() && addatt.getText().isEmpty());
       }
    };

    final Button b2 = new Button("Add");
    b2.disableProperty().bind(bb);

This is my code to disable Button when the TextFields are empty, that is the Button becomes active when all the TextField are filled. But this code is not working. When one TextField is filled the Button becomes active. I had used this code at other parts of my project for this same purpose add it is working fine there. Why is it not working here ?

回答1:

If you want the Button to be active if and only if all fields are filled (i.e. not empty), then you are using the wrong operator. Use || instead of && to make it work.

You can easyly see what's wrong, if you reformulate the formula from computeValue using DeMorgan's laws; I write

a1, a2, ..., a6

instead of

`addnum.getText().isEmpty()`, `addt1.getText().isEmpty()`, ..., `addatt.getText().isEmpty()`:

the following statements are equivalent:

  • the button is active
  • !(a1 && a2 && ... && a6)
  • (!a1 || !a2 ||...|| !a6)
  • at least one field is filled

In contrast to that with || instead of &&:

the following statements are equivalent:

  • the button is active
  • !(a1 || a2 || ... || a6)
  • (!a1 && !a2 &&...&& !a6)
  • all fields are filled