Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enabling/Disabling buttons in JavaFX [duplicate]

Tags:

java

javafx

how do you disable buttons under a certain condition? For example, i have many text fields and buttons, when those text fields are empty one of my buttons should be disabled. i already have this code.

if(txtID.getText().isEmpty()&&txtG.getText().isEmpty()
            &&txtBP.getText().isEmpty()&&txtD.getText().isEmpty()
            &&txtSP.getText().isEmpty()&&txtCons.getText().isEmpty()){
       btnAdd.setDisable(true);
       }
else{
btnAdd.setDisable(false);
}

is there an easier way to do this? Also if i add text into those areas shouldnt the button be re enable its self?

like image 506
user3505212 Avatar asked Apr 15 '15 03:04

user3505212


1 Answers

Create a BooleanBinding using the textfield's textProperty() and then bind it with the Button's disableProperty().

For enabling the button if any of the textfields is not empty.

// I have added 2 textFields, you can add more...
BooleanBinding booleanBind = Bindings.and(text1.textProperty().isEmpty(),
                                              text2.textProperty().isEmpty());
button.disableProperty().bind(booleanBind);

For more than 2 textfields

BooleanBinding booleanBind = Bindings.and(text1.textProperty().isEmpty(),
          text2.textProperty().isEmpty()).and(text3.textProperty().isEmpty());

Or, a better approach is to use and directly on the property:

BooleanBinding booleanBind = text1.textProperty().isEmpty()
                            .and(text2.textProperty().isEmpty())
                                      .and(text3.textProperty().isEmpty());

For enabling the button only if all of the textfields have text.

Just replace and with or.

BooleanBinding booleanBind = text1.textProperty().isEmpty()
                            .or(text2.textProperty().isEmpty())
                                      .or(text3.textProperty().isEmpty());
like image 120
ItachiUchiha Avatar answered Oct 02 '22 07:10

ItachiUchiha