Enumerating the Lines in a JTextArea Component - Java Swing

Java examples for Swing:JTextArea

Description

Enumerating the Lines in a JTextArea Component

Demo Code

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

public class Main {
  public static void main(String[] argv) {
    JTextArea textArea = new JTextArea("word1 word2\nword3\nword4");
    Element paragraph = textArea.getDocument().getDefaultRootElement();
    int contentCount = paragraph.getElementCount();

    for (int i = 0; i < contentCount; i++) {
      Element e = paragraph.getElement(i);
      int rangeStart = e.getStartOffset();
      int rangeEnd = e.getEndOffset();
      try {//from  ww w . j  ava 2s.c  o  m
        String line = textArea.getText(rangeStart, rangeEnd - rangeStart);
        System.out.println(line);
      } catch (BadLocationException ex) {
      }
    }
    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();
        try {
          String line = textArea.getText(rangeStart, rangeEnd - rangeStart);
          System.out.println(line);
        } catch (BadLocationException ex) {
        }
      }
    }
  }
}

Related Tutorials