LimitText

JTextComponent textComp = new JTextField();
textComp.setDocument(new FixedSizePlainDocument(10));

class FixedSizePlainDocument extends PlainDocument {
    int maxSize;

    public FixedSizePlainDocument(int limit) {
        maxSize = limit;
    }

    public void insertString(int offs, String str, AttributeSet a) throws BadLocationException {
        if ((getLength() + str.length()) <= maxSize) {
            super.insertString(offs, str, a);
        } else {
            throw new BadLocationException("Insertion exceeds max size of document", offs);
        }
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.