Java examples for Swing:JTextComponent
Retrieving All the Text from a JTextComponent Efficiently
import java.text.CharacterIterator; import javax.swing.JTextPane; import javax.swing.text.BadLocationException; import javax.swing.text.Document; import javax.swing.text.JTextComponent; import javax.swing.text.Segment; public class Main { public static void main(String[] argv) { // 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;/*w ww . j a v a2 s. c o m*/ 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); 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) { } } }