Enumerating the Paragraphs of a JTextPane Component - Java Swing

Java examples for Swing:JTextPane

Description

Enumerating the Paragraphs of a JTextPane Component

Demo Code

import javax.swing.JTextPane;
import javax.swing.text.BadLocationException;
import javax.swing.text.Element;

public class Main {
  public static void main(String[] args) throws Exception {
    // Create a text pane
    JTextPane textPane = new JTextPane();

    // Get section element
    Element section = textPane.getDocument().getDefaultRootElement();

    int paraCount = section.getElementCount();

    // Get index ranges for each paragraph
    for (int i = 0; i < paraCount; i++) {
      Element e = section.getElement(i);
      int rangeStart = e.getStartOffset();
      int rangeEnd = e.getEndOffset();
      try {/*  www . ja  v a  2  s  . co m*/
        String para = textPane.getText(rangeStart, rangeEnd - rangeStart);
      } catch (BadLocationException ex) {
      }
    }
  }
}

Related Tutorials