How to set limit of length inside JTextField?

43 Views Asked by At

I'm working on a Java Swing application that involves the use of JTextField for user input. I want to restrict the minimum and maximum length of text that users can enter into the JTextField component. However, the standard JTextField does not provide a built-in method to set such a limit, and i'm looking for a way to implement this functionality to ensure that users cannot input more digits than the specified limit. Minimum & Maximum = 6 digits

Problem solved with this code

max.setDocument(new Limit(6)); Limit as New Class

import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;

class Limit extends PlainDocument {

    private static final long serialVersionUID = 1L;
    private int limit;

    public Limit(int limit) {
        this.limit = limit;
    }

    @Override
    public void insertString(int offset, String str, AttributeSet attr) throws BadLocationException {
        if (str == null) {
            return;
        }

        if ((getLength() + str.length()) <= limit) {
            super.insertString(offset, str, attr);
        }
    }
}
0

There are 0 best solutions below