Search code examples
javaswingjtextfield

Allow only numbers in JTextfield


I'm trying to implement requirements like:

Accept only numbers in JTextield, when a non-digit key pressed, it will not be accepted.

I tried many stuff, even tried to call the backspace event to remove the last character if it's a non-digit. However, not able to remove the value typed in the textfield. I tried to understand DOCUMENT FILTER but finding it difficult to implement. I will be glad if anyone helps me to resolve the issue.


Solution

  • Use DocumentFilter. Here is simple example with regex:

    JTextField field = new JTextField(10);
    ((AbstractDocument)field.getDocument()).setDocumentFilter(new DocumentFilter(){
            Pattern regEx = Pattern.compile("\\d*");
    
            @Override
            public void replace(FilterBypass fb, int offset, int length, String text, AttributeSet attrs) throws BadLocationException {          
                Matcher matcher = regEx.matcher(text);
                if(!matcher.matches()){
                    return;
                }
                super.replace(fb, offset, length, text, attrs);
            }
        });
    

    field is your JTextField, and this filter allow to enter only digits.