Limiting the Capacity of a JTextComponent

Prior to J2SE 1.4, limiting the capacity of a text component involved overriding the insertString() method of the component's model. Here's an example:
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);
        }
    }
}
J2SE 1.4 allows the ability to filter all editing operations on a text component. Here's an example that uses the new filtering capability to limit the capacity of the text component:
JTextComponent textComponent = new JTextField();
AbstractDocument doc = (AbstractDocument)textComponent.getDocument();
doc.setDocumentFilter(new FixedSizeFilter(10));

class FixedSizeFilter extends DocumentFilter {
    int maxSize;

    // limit is the maximum number of characters allowed.
    public FixedSizeFilter(int limit) {
        maxSize = limit;
    }

    // This method is called when characters are inserted into the document
    public void insertString(DocumentFilter.FilterBypass fb, int offset, String str,
            AttributeSet attr) throws BadLocationException {
        replace(fb, offset, 0, str, attr);
    }

    // This method is called when characters in the document are replace with other characters
    public void replace(DocumentFilter.FilterBypass fb, int offset, int length,
            String str, AttributeSet attrs) throws BadLocationException {
        int newLength = fb.getDocument().getLength()-length+str.length();
        if (newLength <= maxSize) {
            fb.replace(offset, length, str, attrs);
        } else {
            throw new BadLocationException("New characters exceeds max size of document", offset);
        }
    }
}

Comments

15 Apr 2010 - 12:42am by coder (not verified)

Thanx!

29 Nov 2011 - 12:03am by Sudheer (not verified)

Really Helpful thnx

Post a comment

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Image CAPTCHA
Enter the characters shown in the image. Ignore spaces and be careful about upper and lower case.