Reputation: 1996
I have a piece of code, a login form in JavaFX. It is just a prototype, and it is basing on a tutorial which hasnt covered a topic like that. I want to add a TextField validation, I did it like this:
Button btn = new Button("Login");
HBox hBtn = new HBox(10);
hBtn.setAlignment(Pos.BOTTOM_RIGHT);
hBtn.getChildren().add(btn);
grid.add(hBtn, 1, 4);
final Text actiontarget = new Text();
grid.add(actiontarget, 1, 6);
if (userTextField.getText().trim().isEmpty() && !pwField.getText().trim().isEmpty()) {
btn.setOnAction(event
-> {
actiontarget.setFill(Color.FIREBRICK);
actiontarget.setText("No login provided!");
});
} else if (pwField.getText().trim().isEmpty() && !userTextField.getText().trim().isEmpty()) {
btn.setOnAction(event
-> {
actiontarget.setFill(Color.FIREBRICK);
actiontarget.setText("Please provide a password!");
});
} else if (userTextField.getText().trim().isEmpty() && pwField.getText().trim().isEmpty()) {
btn.setOnAction(event
-> {
actiontarget.setFill(Color.FIREBRICK);
actiontarget.setText("Please provide login and password!");
});
} else {
btn.setOnAction(event
-> {
actiontarget.setFill(Color.GREEN);
actiontarget.setText("Login succesfull");
});
}
The problem is, that this code ALWAYS returning the text from the 3rd condition: Please provide login and password!
, the input in those fields doesnt matter. I can provide only password, only login, both, or none of the two, the result will be allways the same.
Am I missing something here? Is this a (very) wrong approach? Or am I just tired and should go to sleep?
Cheers!
Upvotes: 0
Views: 824
Reputation: 82521
The if/else if
is evaluated at the time you create the GUI.
This means the check is done for the values you've initialized the TextField
s with (or the default values).
Move the check to the event handler to do the checks for the values at the time the button is clicked:
...
grid.add(actiontarget, 1, 6);
btn.setOnAction(evt -> {
String user = userTextField.getText().trim();
String password = pwField.getText().trim();
if (!(user.isEmpty() || password.isEmpty())) {
actiontarget.setFill(Color.GREEN);
actiontarget.setText("Login succesfull");
} else {
actiontarget.setFill(Color.FIREBRICK);
if (user.isEmpty()) {
actiontarget.setText(password.isEmpty() ? "Please provide login and password!" : "No login provided!");
} else {
actiontarget.setText("Please provide a password!");
}
}
});
Upvotes: 2