Set Max Character Length Of JTextField


There is no way to directly set a JTextField‘s maximum character length. The only way for you to do that is to create your own class that inherits the PlainDocument class, instantiate an object of that class and call the JTextField method setDocument().

Below is the source for the custom made MaxLengthTextDocument class.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class MaxLengthTextDocument extends PlainDocument {
    private int maxChars;
 
    public MaxLengthTextDocument(int length) {
        maxChars = length;
    }
 
    @Override
    public void insertString(int offs, String str, AttributeSet a)throws BadLocationException {
        if(str == null || (getLength() + str.length() > maxChars)){
            str = str.substring(0, maxChars);
        }
        super.insertString(offs, str, a);
    }
}

Found this post useful? Buy me a cup of coffee or help support the sponsors on the right.

Related Posts with Thumbnails