![]() |
The Java Developers Almanac 1.4Order this book from Amazon. |
e969. Retrieving All the Text from a JTextComponent EfficientlyThe text contained in a text component is not always stored contiguously. Therefore, retrieving text usinggetText() may
cause a new String object to be created and the text copied to
the new string. If you do not need the text in one contiguous chunk,
the most efficient way to retrieve the text is in pieces called
segments. This example retrieves the entire contents of a text
component in segments.
// Create the text component JTextComponent textComp = new JTextPane(); Document doc = textComp.getDocument(); // Create a segment to hold the characters in the document Segment segment = new Segment(); int pos = 0; segment.setPartialReturn(true); try { // Retrieve all segments while (pos < doc.getLength()) { // Ask for the remainder of the document text doc.getText(pos, doc.getLength()-pos, segment); // You can access the contents directly from the array in the segment. // Never modify the contents of the array for (int i=0; i<segment.count; i++) { int positionInDoc = pos+i; char charAtPos = segment.array[i+segment.offset]; } // Or use the segment as a character iterator int i=0; for(char c=segment.first(); c != CharacterIterator.DONE; c=segment.next(), i++) { int positionInDoc = pos+i; char charAtPos = c; } // Increment pos by the actual number of characters retrieved pos += segment.count; } } catch (BadLocationException e) { }
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 e975. Limiting the Capacity of 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. |