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()) 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 fb.replace(offset, length, str, attrs);
} else {
throw new BadLocationException("New characters exceeds max size of document", offset);
}
}
}