Asynchronously Reading the Contents of a Visible JTextComponent - Java Swing

Java examples for Swing:JTextComponent

Description

Asynchronously Reading the Contents of a Visible JTextComponent

Demo Code


import java.awt.BorderLayout;

import javax.swing.JFrame;
import javax.swing.JTextArea;
import javax.swing.text.Document;
import javax.swing.text.JTextComponent;

public class Main {
  public static void main(String[] args) {
    // 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();/*from w  w w  .ja va 2  s  .  c  om*/
    frame.setVisible(true);

    // Read the contents
    try {

      read(doc);
    } catch (Exception e) {
    }
  }

  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;
  }

}

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 Tutorials