![]() |
The Java Developers Almanac 1.4Order this book from Amazon. |
e975. Limiting the Capacity of a JTextComponentPrior to J2SE 1.4, limiting the capacity of a text component involved overriding theinsertString() 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); } } }
e969. Retrieving All the Text from a JTextComponent Efficiently e970. Modifying Text in a JTextComponent e971. Asynchronously Reading the Contents of a Visible JTextComponent e972. Finding Word Boundaries in a JTextComponent e973. Retrieving the Visible Lines in a JTextComponent e974. Using a Position in a JTextComponent e976. Enabling Text-Dragging on a JTextComponent e977. Sharing a Document Between JTextComponents e978. Enumerating All the Views in a JTextComponent
© 2002 Addison-Wesley. |