简体   繁体   English

如果textfield包含数字,请检查运行时

[英]Check on runtime if textfield contains a number

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. 我试图找出如何检查运行时是否在文本字段中输入数字,然后我想要执行Backspace以自行删除它。 My code is @FXML public void onKeyTyped(KeyEvent event) { if (!(event.getText().matches("[az]"))) { event.consume(); } } 我的代码是@FXML public void onKeyTyped(KeyEvent event) { if (!(event.getText().matches("[az]"))) { event.consume(); } } @FXML public void onKeyTyped(KeyEvent event) { if (!(event.getText().matches("[az]"))) { 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! 任何输入都非常感谢!

Im guessing its because you are checking az when you should be checking 0-9. 我猜它是因为你在检查时应检查0-9。

Edit: Oops, you're right I missed the !. 编辑:哎呀,你说得对,我错过了! As to it being runtime, aren't all events runtime? 至于它是运行时,是不是所有事件运行时?

you could try this (FX11 Only) 你可以试试这个(仅限FX11)

    //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(). 请注意,这使用event.getCharacter()而不是event.getText()。 For me getText() is always empty,as in this link: 对我来说,getText()总是空的,就像在这个链接中一样:

JavaFX KeyEvent.getText() returns empty? JavaFX KeyEvent.getText()返回空?

Not also if you wish to go your original route of checking if it's not equal to az remember to account for AZ as well. 如果您希望使用原始检查路线,如果它不等于az,请记住也要考虑AZ。 Or convert the character to lower case before checking as matches is case specific. 或者在检查之前将字符转换为小写,因为匹配是特定于案例的。

FX8 Only 仅限FX8

if (event.getCharacter().matches("[0-9]"))
    {
        event.consume();

    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM