// 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;

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;, i++) {
            int positionInDoc = pos+i;
            char charAtPos = c;

        // Increment pos by the actual number of characters retrieved
        pos += segment.count;
} catch (BadLocationException e) {

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.