Issue
I am trying to figure out how i can check on runtime whether a number is being entered on a textfield and i want then to execute a Backspace to delete it on its own. My code is
@FXML
public void onKeyTyped(KeyEvent event) {
if (!(event.getText().matches("[a-z]"))) {
event.consume();
}
}
I dont understand why it's not working. Maybe i dont understand the concept of changing something on runtime. Any input is greatly appreciated!
Solution
you could try this (FX11 Only)
//check if character typed is a number
if (event.getCharacter().matches("[0-9]"))
{
event.consume();
//move caret back one step as we do not want the typed digit
//and want the caret to remain after last entered text
textField.backward();
//delete the typed digit
textField.deleteNextChar();
}
Note this uses event.getCharacter() instead of event.getText(). For me getText() is always empty,as in this link:
JavaFX KeyEvent.getText() returns empty?
Not also if you wish to go your original route of checking if it's not equal to a-z remember to account for A-Z as well. Or convert the character to lower case before checking as matches is case specific.
FX8 Only
if (event.getCharacter().matches("[0-9]"))
{
event.consume();
}
Answered By - user11321608