How to make it so that you can enter only numbers in JTextField ?

    1 answer 1

    This is done using DocumentFilter

     class DigitFilter extends DocumentFilter { private static final String DIGITS = "\\d+"; @Override public void insertString(FilterBypass fb, int offset, String string, AttributeSet attr) throws BadLocationException { if (string.matches(DIGITS)) { super.insertString(fb, offset, string, attr); } } @Override public void replace(FilterBypass fb, int offset, int length, String string, AttributeSet attrs) throws BadLocationException { if (string.matches(DIGITS)) { super.replace(fb, offset, length, string, attrs); } } } 

    After that you must assign this filter to the field.

     JTextField textField = new JTextField(); PlainDocument doc = (PlainDocument) textField.getDocument(); doc.setDocumentFilter(new DigitFilter());