Java Swing How to - Enumerate the content elements with a ElementIterator in JTextArea








Question

We would like to know how to enumerate the content elements with a ElementIterator in JTextArea.

Answer

  //w  w w . j  a  v a2  s  .c om


import javax.swing.JTextArea;
import javax.swing.text.Document;
import javax.swing.text.Element;
import javax.swing.text.ElementIterator;

public class Main {
  public static void main(String[] argv) throws Exception {
    JTextArea textArea = new JTextArea("word1 word2\nword3\nword4");
    Document doc = textArea.getDocument();
    ElementIterator it = new ElementIterator(doc.getDefaultRootElement());
    Element e;
    while ((e = it.next()) != null) {
      if (e.isLeaf()) {
        int rangeStart = e.getStartOffset();
        int rangeEnd = e.getEndOffset();

        String line = textArea.getText(rangeStart, rangeEnd - rangeStart);
        System.out.println(line);
      }
    }
  }
}