I have a Swing program where work is continuously being done in a non-Swing thread. It often needs to update a JTextPane — frequently many times per second. I realize that setText() needs to be called from back inside the event-dispatching thread, but I cant figure out how to make this happen smoothly.
The following minimal complete example is as close as I’ve been able to get it, using a PipedInputStream/PipedOutputStream pair, but this only seems to update the screen once every second or so. I’m not sure what’s taking so long.
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
public class TextTest extends JFrame {
private JTextPane out = new JTextPane();
private PipedInputStream pIn = new PipedInputStream();
private PrintWriter pOut;
public TextTest() {
try {
pOut = new PrintWriter(new PipedOutputStream(pIn));
}
catch (IOException e) {System.err.println("can't init stream");}
add(new JScrollPane(out));
setSize(500, 300);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
// Start a loop to print to the stream continuously
new Thread() {
public void run() {
for (int i = 0; true; i++) {
pOut.println(i);
}
}
}.start();
// Start a timer to display the text in the stream every 10 ms
new Timer(10, new ActionListener() {
public void actionPerformed (ActionEvent evt) {
try {
if (pIn.available() > 0) {
byte[] buffer = new byte[pIn.available()];
pIn.read(buffer);
out.setText(out.getText() + new String(buffer));
}
}
catch (IOException e) {System.err.println("can't read stream");}
}
}).start();
}
public static void main(String[] args) {
new TextTest();
}
}
Am I implementing this wrong? Do I just have totally the wrong idea about how to continuously update a JTextPane from outside the EDT?
The
setText()“method is thread safe, although most Swing methods are not. Please see How to Use Threads for more information.”Addendum: For reference, here’s some other approaches to updating on the EDT. Another thing to note is that the action event handler for
javax.swing.Timerexecutes on the EDT. Here’s my variation: