0

I want to make a JTextField accept only number. And I found solution here.

    ((AbstractDocument)textField_time.getDocument()).setDocumentFilter(new DocumentFilter() {

        @Override
        public void insertString(DocumentFilter.FilterBypass fb, int offset, String str, AttributeSet a) throws BadLocationException {
            fb.insertString(offset, str.replaceAll("\\D++", ""), a);
        }

    });

Above is my code, and alphabet can still be typed in;

Community
  • 1
  • 1
bijiDango
  • 1,385
  • 3
  • 14
  • 28

1 Answers1

4

You also need to override the replace(...) method of the DocumentFilter. This is the method that gets invoked by the Swing text components as you enter text via the GUI.

The insertString(...) method is only invoked when update the Document directly by using:

Document doc = textField_time.getDocument();
doc.insertString(...);

Check out the section from the Swing tutorial on Implementing a Document Filter for a complete implementation. You can even turn the "debug" variable on to verify that the replace() method is invoked.

camickr
  • 321,443
  • 19
  • 166
  • 288