Java examples for Swing:JTextArea
Enumerating the Lines in a JTextArea Component
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) { } } } } }