如何过滤退格键输入

How to filter a backspace keyboard input

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

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 语句中?

我想这应该可行

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

我找到了答案:

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];
                int codeBackSpace = ch;
                if (!(ch >= '0' && ch <= '9') && codeBackSpace!=8) {

                    System.out.println("The char you entered is not a number");
                    t.consume();
                }
            }
        });