您必须使用SwingUtilities.invokeLater,因为只能从事件派发线程访问Swing组件。
这个方法的javadoc有一个关于线程的Swing教程的链接。点击此链接。
这是一个例子:
public class SwingWithThread {
private JLabel label;
// ...
public void startBackgroundThread() {
Runnable r = new Runnable() {
@Override
public void run() {
try {
// simulate some background work
Thread.sleep(5000L);
}
catch (InterruptedException e) {
// ignore
}
// update the label IN THE EDT!
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
label.setText("Background thread has stopped");
}
});
};
};
new Thread(r).start();
}
}