ConcurReadText

// 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();
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.