Java Swing How to - Get all the Lines in a JTextArea








Question

We would like to know how to get all the Lines in a JTextArea.

Answer

/*  w  ww  .ja  v a 2  s  .  c o  m*/


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

public class Main {
  public static void main(String[] argv) throws Exception {
    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();
      String line = textArea.getText(rangeStart, rangeEnd - rangeStart);
      System.out.println(line);
    }
  }
}