Enumerating the Lines in a JTextArea Component

The contents of a text component are stored in a Document object that, in turn, breaks the content into a hierarchy of Element objects. In the case of a text area, each line of text (a contiguous span of characters terminated by a single newline) is stored in a content element. For example, if the last line of the contents is terminated by a newline and there are 100 new lines, there will be 100 content elements. All content elements are stored under a single paragraph element.

This example demonstrates how to retrieve the paragraph element and enumerate all children content elements.

See also Retrieving the Visible Lines in a JTextComponent.

// Create a text area JTextArea textArea = new JTextArea("word1 word2\nword3\nword4"); // Get paragraph element Element paragraph = textArea.getDocument().getDefaultRootElement(); // Get number of content elements int contentCount = paragraph.getElementCount(); // Get index ranges for each content element. // Each content element represents one line. // Each line includes the terminating newline. for (int i=0; i<contentCount; i++) { Element e = paragraph.getElement(i); int rangeStart = e.getStartOffset(); int rangeEnd = e.getEndOffset(); try { String line = textArea.getText(rangeStart, rangeEnd-rangeStart); } catch (BadLocationException ex) { } }
Here is another way to enumerate the content elements with a ElementIterator:
// Get the text area's document Document doc = textArea.getDocument(); // Create an iterator using the root element ElementIterator it = new ElementIterator(doc.getDefaultRootElement()); // Iterate all content elements (which are leaves) Element e; while ((e=it.next()) != null) { if (e.isLeaf()) { int rangeStart = e.getStartOffset(); int rangeEnd = e.getEndOffset(); try { String line = textArea.getText(rangeStart, rangeEnd-rangeStart); } catch (BadLocationException ex) { } } }

Comments

9 Feb 2010 - 1:15am by NKM (not verified)

Brilliant ! Thank you.

Post a comment

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Image CAPTCHA
Enter the characters shown in the image. Ignore spaces and be careful about upper and lower case.