1

I'm using java swing and trying to enter Numbers only into a JTextField.

when typing a char I want to show an Invalid message, and prevent from typing the char into the 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!");
            }
        }
    });

for some reason, e.consume() doesnt work as I expected, and i can type chars.

George Z.
  • 6,643
  • 4
  • 27
  • 47
Assaf
  • 21
  • 1
  • 3

1 Answers1

4

Generally, adding a custom KeyListener to prevent characters in a JTextField is not recommended. It would be better for users (and easier for you as programmer) to use a component that it has been created for only-numbers input.

  1. JSpinner is one of them.
  2. JFormattedTextField is another one.

If you insist of doing it your self though, it would be better to achieve it with a DocumentFilter and not with a KeyListener. Here is another example as well.

In addition to these examples, here is my solution:

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();
        }
    }
}
George Z.
  • 6,643
  • 4
  • 27
  • 47