The Java Developers Almanac 1.4


Order this book from Amazon.

   
Home > List of Packages > javax.swing.text  [49 examples] > JTextComponent  [11 examples]

e973. Retrieving the Visible Lines in a JTextComponent

There are hard and soft line breaks when viewing the contents of a text component. Hard line breaks are caused by a newline character in the contents. Soft line breaks are a result of word wrapping by the text component. Word wrapping occurs strictly on the display; it does not change the contents (i.e., newlines are not inserted into the contents).

This example demonstrates how to retrieve the contents with soft line breaks. The retrieval does not modify the contents; it returns the contents with additional newlines for soft line breaks.

Note: getWrappedLines() can be used directly if called within an event thread. To call it on a visible text component outside an event thread, use the Document.render() method to safely retrieve the text. See e971 Asynchronously Reading the Contents of a Visible JTextComponent for an example.

    // Returns null if comp does not have a size
    public static String getWrappedText(JTextComponent c) {
        int len = c.getDocument().getLength();
        int offset = 0;
    
        // Increase 10% for extra newlines
        StringBuffer buf = new StringBuffer((int)(len*1.10));
    
        try {
            while (offset < len) {
                int end = Utilities.getRowEnd(c, offset);
                if (end < 0) {
                    break;
                }
    
                // Include the last character on the line
                end = Math.min(end+1, len);
    
                String s = c.getDocument().getText(offset, end-offset);
                buf.append(s);
    
                // Add a newline if s does not have one
                if (!s.endsWith("\n")) {
                    buf.append('\n');
                }
                offset = end;
            }
        } catch (BadLocationException e) {
        }
        return buf.toString();
    }

 Related Examples
e968. Retrieving Text from a JTextComponent
e969. Retrieving All the Text from a JTextComponent Efficiently
e970. Modifying Text in a JTextComponent
e971. Asynchronously Reading the Contents of a Visible JTextComponent
e972. Finding Word Boundaries in a JTextComponent
e974. Using a Position in a JTextComponent
e975. Limiting the Capacity of a JTextComponent
e976. Enabling Text-Dragging on a JTextComponent
e977. Sharing a Document Between JTextComponents
e978. Enumerating All the Views in a JTextComponent

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


© 2002 Addison-Wesley.