防止在java swing JTextField上输入字符

防止在java swing JTextField上输入字符,java,swing,jtextfield,keylistener,Java,Swing,Jtextfield,Keylistener,我正在使用JavaSwing并尝试只在JTextField中输入数字 idText.addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { try { int i = Integer.parseInt(idText.getText()+e.getKeyChar())

我正在使用JavaSwing并尝试只在JTextField中输入数字

        idText.addKeyListener(new KeyAdapter() {
        @Override
        public void keyPressed(KeyEvent e) {
            try
            {
                int i = Integer.parseInt(idText.getText()+e.getKeyChar());
                validText.setText("");
            }
            catch(NumberFormatException e1) {
                e.consume();
                validText.setText("Numbers Only!");
            }
        }
    });
键入字符时,我希望显示一条无效消息,并防止在JTextField中键入字符

        idText.addKeyListener(new KeyAdapter() {
        @Override
        public void keyPressed(KeyEvent e) {
            try
            {
                int i = Integer.parseInt(idText.getText()+e.getKeyChar());
                validText.setText("");
            }
            catch(NumberFormatException e1) {
                e.consume();
                validText.setText("Numbers Only!");
            }
        }
    });

由于某些原因,e.consume不能像我预期的那样工作,我可以键入chars。

通常,不建议添加自定义KeyListener以防止JTextField中出现字符。对于用户来说,使用一个只为数字输入而创建的组件会更好,对于程序员来说也更容易

是其中之一。 这是另一个。 如果你坚持自己去做,最好是用一个键盘而不是一个键盘监听器。这也是另一个例子

除了这些示例之外,以下是我的解决方案:

public class DocumentFilterExample extends JFrame {
    public DocumentFilterExample() {
        super("example");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLayout(new FlowLayout());

        JTextField field = new JTextField(15);
        AbstractDocument document = (AbstractDocument) field.getDocument();
        document.setDocumentFilter(new OnlyDigitsDocumentFilter());
        add(field);

        setLocationByPlatform(true);
        pack();
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> new DocumentFilterExample().setVisible(true));
    }

    private static class OnlyDigitsDocumentFilter extends DocumentFilter {
        @Override
        public void replace(FilterBypass fb, int offset, int length, String text, AttributeSet attrs) throws BadLocationException {
            text = keepOnlyDigits(text);
            super.replace(fb, offset, length, text, attrs);
        }

        @Override
        public void insertString(FilterBypass fb, int offset, String string, AttributeSet attr) throws BadLocationException {
            string = keepOnlyDigits(string);
            super.insertString(fb, offset, string, attr);
        }

        private String keepOnlyDigits(String text) {
            StringBuilder sb = new StringBuilder();
            text.chars().filter(Character::isDigit).forEach(sb::append);
            return sb.toString();
        }
    }
}

通常,不建议添加自定义KeyListener以防止JTextField中出现字符。对于用户来说,使用一个只为数字输入而创建的组件会更好,对于程序员来说也更容易

是其中之一。 这是另一个。 如果你坚持自己去做,最好是用一个键盘而不是一个键盘监听器。这也是另一个例子

除了这些示例之外,以下是我的解决方案:

public class DocumentFilterExample extends JFrame {
    public DocumentFilterExample() {
        super("example");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLayout(new FlowLayout());

        JTextField field = new JTextField(15);
        AbstractDocument document = (AbstractDocument) field.getDocument();
        document.setDocumentFilter(new OnlyDigitsDocumentFilter());
        add(field);

        setLocationByPlatform(true);
        pack();
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> new DocumentFilterExample().setVisible(true));
    }

    private static class OnlyDigitsDocumentFilter extends DocumentFilter {
        @Override
        public void replace(FilterBypass fb, int offset, int length, String text, AttributeSet attrs) throws BadLocationException {
            text = keepOnlyDigits(text);
            super.replace(fb, offset, length, text, attrs);
        }

        @Override
        public void insertString(FilterBypass fb, int offset, String string, AttributeSet attr) throws BadLocationException {
            string = keepOnlyDigits(string);
            super.insertString(fb, offset, string, attr);
        }

        private String keepOnlyDigits(String text) {
            StringBuilder sb = new StringBuilder();
            text.chars().filter(Character::isDigit).forEach(sb::append);
            return sb.toString();
        }
    }
}

用按键类型替换按键方法有效吗?用按键类型替换按键方法有效吗?1000票赞成不使用按键监听器1000票赞成不使用按键监听器