【问题标题】:Prevent char entering on java swing JTextField防止在java swing JTextField上输入字符
【发布时间】:2020-09-01 11:38:56
【问题描述】:

我正在使用 java swing 并尝试仅在 JTextField 中输入数字。

在输入字符时,我想显示无效消息,并防止在 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() 没有按我的预期工作,我可以输入字符。

【问题讨论】:

  • keyTyped 替换keyPressed 方法有效吗?

标签: java swing jtextfield keylistener


【解决方案1】:

一般来说,不建议添加自定义KeyListener 来防止JTextField 中出现字符。用户最好(作为程序员也更容易)使用为仅数字输入而创建的组件。

  1. JSpinner 就是其中之一。
  2. JFormattedTextField 是另一个。

如果您坚持自己做,最好使用DocumentFilter 而不是KeyListenerHere 也是另一个例子。

除了这些例子,这里是我的解决方案:

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 票推荐不要使用 KeyListener
猜你喜欢
  • 2013-04-29
  • 1970-01-01
  • 1970-01-01
  • 2012-07-28
  • 2012-01-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-29
相关资源
最近更新 更多