如何过滤退格键盘输入

时间:2015-04-29 17:16:51

标签: java javafx-2

我有这个代码,当按下另一个键作为数字时会给出一条消息:

txtValueOfClause.addEventFilter(KeyEvent.KEY_TYPED, new EventHandler<KeyEvent>() {
            @Override
            public void handle(KeyEvent t) {
                char ar[] = t.getCharacter().toCharArray();
                char ch = ar[t.getCharacter().toCharArray().length - 1];
                if (!(ch >= '0' && ch <= '9')) {
                    System.out.println("The char you entered is not a number");
                    t.consume();
                }
            }
        });

现在,如果我按错了按钮并按退格键将其删除,我也会收到此错误消息。 如何在if语句中添加退格输入?

1 个答案:

答案 0 :(得分:0)

我猜这应该有用

txtValueOfClause.addEventFilter(KeyEvent.KEY_TYPED, new EventHandler<KeyEvent>() {
        @Override
        public void handle(KeyEvent t) {
            char ar[] = t.getCharacter().toCharArray();
            char ch = ar[t.getCharacter().toCharArray().length - 1];
            if (!(ch >= '0' && ch <= '9' && t.getCode().equals(KeyCode.BACK_SPACE))) {
                System.out.println("The char you entered is not a number");
                t.consume();
            }
        }
    });