有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

如果textfield包含数字,则在运行时进行java检查

我试图弄清楚如何在运行时检查文本字段中是否输入了一个数字,然后我想执行一个退格来自行删除它。我的代码是 @FXML public void onKeyTyped(KeyEvent event) { if (!(event.getText().matches("[a-z]"))) { event.consume(); } }

我不明白它为什么不起作用。也许我不理解在运行时更改某些内容的概念。非常感谢您的任何意见


共 (2) 个答案

  1. # 1 楼答案

    你可以试试这个(仅限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();
    
        }
    

    注意,它使用事件。getCharacter()而不是事件。getText()。对我来说,getText()始终为空,如以下链接所示:

    JavaFX KeyEvent.getText() returns empty?

    如果你想按照你原来的方法检查它是否不等于a-z,也不要忘了考虑a-z。或者在检查匹配项之前将字符转换为小写,因为匹配项是特定于大小写的

    仅限FX8

    if (event.getCharacter().matches("[0-9]"))
        {
            event.consume();
    
        }
    
  2. # 2 楼答案

    我猜是因为你在检查a-z,而你应该检查0-9

    编辑:哎呀,你说得对,我错过了!。 至于它是运行时的,不是所有的事件都是运行时的吗