The Java Developers Almanac 1.4


Order this book from Amazon.

   
Home > List of Packages > javax.swing.text  [49 examples] > JTextPane  [5 examples]

e990. Enumerating the Paragraphs of a JTextPane Component

The contents of a text component are stored in a Document object that in turn, breaks the content into a hierarchy of Element objects. In the case of a text pane, the content elements contain runs of characters. A run of characters is a contiguous span of characters with the same attributes. Adjacent runs of characters will have different sets of attributes. If the attributes of one run is modified so that it becomes identical to an adjacent run, both runs will be combined into a single run.

Adjacent runs that make up a line of text (a contiguous span of characters terminated by a single newline) are stored under one paragraph element. In other words, a paragraph element will have at most one run (the last run) with a single newline (only the very last line of the contents may lack a newline). Note that the adjacency rule does not apply to runs in different paragraph elements.

Finally, all paragraph elements in a text pane are stored under a single section element.

See also e973 Retrieving the Visible Lines in a JTextComponent.

    // Create a text pane
    JTextPane textPane = new JTextPane();
    
    // Get section element
    Element section = textPane.getDocument().getDefaultRootElement();
    
    // Get number of paragraphs.
    // In a text pane, a span of characters terminated by single
    // newline is typically called a paragraph.
    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 {
            String para = textPane.getText(rangeStart, rangeEnd-rangeStart);
        } catch (BadLocationException ex) {
        }
    }

 Related Examples
e989. Inserting Styled Text in a JTextPane Component
e991. Inserting an Image into a JTextPane Component
e992. Inserting a Component into a JTextPane Component
e993. Customizing Tab Stops in a JTextPane Component

See also: Actions and Key Bindings    Caret and Selection    Events    JEditorPane    JFormattedTextField    JTextArea    JTextComponent    JTextField    Styles   


© 2002 Addison-Wesley.