如何在Java中将消息从工作线程传递到GUI
问题描述:
如何将消息从工作线程传递到Java中的GUI?我知道在Android中这可以通过处理程序和Messages类来实现.但是我希望Java中的同一件事可以帮助任何人.提前致谢.Ranganath.tm
How to pass the message from working thread to GUI in java? I know in Android this can be achieved through handlers and Messages Class. But I want the same thing in Java can any one help me. Thanks in advance. Ranganath.tm
答
You must use SwingUtilities.invokeLater
, because Swing components must only be accessed from the event dispatch thread.
此方法的javadoc包含指向有关线程的Swing教程的链接.点击此链接.
The javadoc of this method has a link to the Swing tutorial about threads. Follow this link.
这是一个例子:
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();
}
}