Enumerate the Lines in a JTextArea Component in Java

Description

The following code shows how to enumerate the Lines in a JTextArea Component.

Example


import java.awt.Font;
//from   ww w .ja  va2  s  . c o m
import javax.swing.JFrame;
import javax.swing.JTextArea;
import javax.swing.text.BadLocationException;
import javax.swing.text.Element;

public class Main extends JFrame {

  public Main() {
    JTextArea textArea = new JTextArea("Initial Text");
    textArea.setFont(new Font("LucidaSans", Font.PLAIN, 40));
    add(textArea);    

    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 = null;
      try {
        line = textArea.getText(rangeStart, rangeEnd - rangeStart);
      } catch (BadLocationException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
      }
      System.out.println(line);
    }
  }

  public static void main(String[] args) {
    JFrame frame = new Main();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    frame.pack();
    frame.setVisible(true);
  }
}

The code above generates the following result.

Enumerate the Lines in a JTextArea Component in Java




















Home »
  Java Tutorial »
    Swing »




Action
Border
Color Chooser
Drag and Drop
Event
Font Chooser
JButton
JCheckBox
JComboBox
JDialog
JEditorPane
JFileChooser
JFormattedText
JFrame
JLabel
JList
JOptionPane
JPasswordField
JProgressBar
JRadioButton
JScrollBar
JScrollPane
JSeparator
JSlider
JSpinner
JSplitPane
JTabbedPane
JTable
JTextArea
JTextField
JTextPane
JToggleButton
JToolTip
JTree
Layout
Menu
Timer