The Java Developers Almanac 1.4


Order this book from Amazon.

   
Home > List of Packages > javax.swing.text  [49 examples] > JTextArea  [7 examples]

e984. Enumerating the Lines in a JTextArea 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 area, each line of text (a contiguous span of characters terminated by a single newline) is stored in a content element. For example, if the last line of the contents is terminated by a newline and there are 100 new lines, there will be 100 content elements. All content elements are stored under a single paragraph element.

This example demonstrates how to retrieve the paragraph element and enumerate all children content elements.

See also e973 Retrieving the Visible Lines in a JTextComponent.

    // Create a text area
    JTextArea textArea = new JTextArea("word1 word2\nword3\nword4");
    
    // Get paragraph element
    Element paragraph = textArea.getDocument().getDefaultRootElement();
    
    // Get number of content elements
    int contentCount = paragraph.getElementCount();
    
    // Get index ranges for each content element.
    // Each content element represents one line.
    // Each line includes the terminating newline.
    for (int i=0; i<contentCount; i++) {
        Element e = paragraph.getElement(i);
        int rangeStart = e.getStartOffset();
        int rangeEnd = e.getEndOffset();
        try {
            String line = textArea.getText(rangeStart, rangeEnd-rangeStart);
        } catch (BadLocationException ex) {
        }
    }
Here is another way to enumerate the content elements with a ElementIterator:
    // Get the text area's document
    Document doc = textArea.getDocument();
    
    // Create an iterator using the root element
    ElementIterator it = new ElementIterator(doc.getDefaultRootElement());
    
    // Iterate all content elements (which are leaves)
    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);
            } catch (BadLocationException ex) {
            }
        }
     }

 Related Examples
e982. Creating a JTextArea Component
e983. Modifying Text in a JTextArea Component
e985. Setting the Tab Size of a JTextArea Component
e986. Moving the Focus with the TAB Key in a JTextArea Component
e987. Enabling Word-Wrapping and Line-Wrapping in a JTextArea Component
e988. Implementing a Console Window with a JTextArea Component

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


© 2002 Addison-Wesley.