'I try to validate input from a TextField, onKeyEvent
When press ENTER a method is executed, and if not show a dialog message to user if no value in the field. Thinking also to do a validation over the input of the user. I've tried this but every time a key is pressed the message dialog pops up.
protected void onTextFieldKeyEnter(KeyEvent event) {
if (event.getCode() == KeyCode.ENTER && !textField.getText().equals("")) {
onHelloButtonClick();
textField.clear();
textField.isFocused();
} else {
Alert alert = new Alert(Alert.AlertType.WARNING);
alert.setTitle("Atentionare");
alert.setHeaderText("Informatia nu este corecta!");
alert.setContentText("Campul nu poate sa fie gol. Introduceti un cif valid");
alert.showAndWait();
}
}
Solution 1:[1]
Your else is executed every time an input was made except of ENTER. So you should change to else if (event.getCode() == KeyCode.ENTER) or move your validation like
if (event.getCode() == KeyCode.ENTER) {
if (!textField.getText().equals("")) {
onHelloButtonClick();
textField.clear();
textField.isFocused();
} else {
Alert alert = new Alert(Alert.AlertType.WARNING);
alert.setTitle("Atentionare");
alert.setHeaderText("Informatia nu este corecta!");
alert.setContentText("Campul nu poate sa fie gol. Introduceti un cif valid");
alert.showAndWait();
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Stefan Warminski |
