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.
以下最低完整的例子与我用管道InputStream/PipedOutputStream乳房接手的情况一样接近,但这似乎只是每秒更新一次。 我不相信花这么久的时间。
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();
}
}
我是否执行这一错误? 我是否对如何从厄立特里亚国防军之外不断更新JTextPane的说法完全错误?