0

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!

ita07
  • 81
  • 10

2 Answers2

0

Im guessing its because you are checking a-z when you should be checking 0-9.

Edit: Oops, you're right I missed the !. As to it being runtime, aren't all events runtime?

Reki
  • 21
  • 4
  • Even if i said 0-9 it doesnt matter because it's not running on runtime. And btw the code is good doing its job haha u must have missed the ! which means not in java. So im basically saying if it doesnt match - > consume – ita07 Apr 12 '19 at 20:42
0

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();

    }
  • This doesnt work at all. textField.deleteNextChar(); returns a boolean which i doesnt work on runtime. – ita07 Apr 13 '19 at 07:05
  • https://docs.oracle.com/javase/8/javafx/api/javafx/scene/control/TextInputControl.html#deleteNextChar-- . As you can see from the link above that deleteNextChar returns true if it deleted the character false if it didn't. I have tested the code in FX11 and it works as you described how you wanted it to work. I suspect you didn't even try the code. –  Apr 13 '19 at 14:12
  • Just tried with FX8 and yes it doesn't work in that environment. In FX8 just consume the event under getCharacter() and it will work. See edited answer. –  Apr 13 '19 at 14:28
  • No i tried the code but it didnt do the job i described. I managed to do it another way with TextFormatter. – ita07 Apr 13 '19 at 14:29
  • Yes sorry I didn't realize the code wouldn't work with FX8 and you hadn't specified a version, anyway I updated my answer so that there is code that works with FX8. Note the FX8 version does not work in Fx11 and vice versa. –  Apr 13 '19 at 14:32
  • Oops , my bad you're right. I ended up doing it by passing a filter but your code works too thanks a lot! – ita07 Apr 14 '19 at 12:20