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.
Here is another way to enumerate the content elements with a
ElementIterator:
// 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) {
}
}
// 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) {
}
}
}
Brilliant ! Thank you.