The Java Developers Almanac 1.4


Order this book from Amazon.

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

e971. Asynchronously Reading the Contents of a Visible JTextComponent

When a text component is visible on the screen, you cannot simply call getText() on the document model to retrieve the text. The reason is that the user may be modifying the text at the same time. There are two ways to safely access the contents of the text component. One is by using SwingUtilities.invokeLater() and the other is by using Document.render(). This example demonstrates the latter.
    // Create and display the component
    JTextComponent textComp = new JTextArea();
    Document doc = textComp.getDocument();
    
    JFrame frame = new JFrame();
    frame.getContentPane().add(textComp, BorderLayout.CENTER);
    frame.pack();
    frame.setVisible(true);
    
    // Read the contents
    try {
        process(read(doc));
    } catch (InterruptedException e) {
    } catch (Exception e) {
    }
    
    // This method returns the contents of a Document using a renderer.
    public static String read(Document doc) throws InterruptedException, Exception {
        Renderer r = new Renderer(doc);
        doc.render(r);
    
        synchronized (r) {
            while (!r.done) {
                r.wait();
                if (r.err != null) {
                    throw new Exception(r.err);
                }
            }
        }
        return r.result;
    }
    
    static class Renderer implements Runnable {
        Document doc;
        String result;
        Throwable err;
        boolean done;
    
        Renderer(Document doc) {
            this.doc = doc;
        }
        public synchronized void run() {
            try {
                result = doc.getText(0, doc.getLength());
            } catch (Throwable e) {
                err = e;
                e.printStackTrace();
            }
            done = true;
            // When done, notify the creator of this object
            notify();
        }
    }

 Related Examples
e968. Retrieving Text from a JTextComponent
e969. Retrieving All the Text from a JTextComponent Efficiently
e970. Modifying Text in a JTextComponent
e972. Finding Word Boundaries in a JTextComponent
e973. Retrieving the Visible Lines 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.