有没有办法阻止主线程直到 Swingworker 完成?
可能的重复:
如何等待 SwingWorker 的 doInBackground() 方法?
我读到这样做确实很糟糕,但我认为这是我实现目标的最佳方式...... 在下面的示例中,有没有办法阻止主线程直到 Swing Worker 完成?
public void flashNode(Node node, int noOfFlashes) {
GraphUpdater updater = new GraphUpdater(node, noOfFlashes);
updater.execute();
}
和 SwingWorker
类
public class GraphUpdater extends SwingWorker<Integer, Integer> {
Node node;
int noOfFlashes;
public GraphUpdater(Node n, int noFlashes) {
node = n;
noOfFlashes = noFlashes;
}
@Override
protected Integer doInBackground() throws Exception {
Color origColor = node.getColor();
for (int i=0; i<noOfFlashes; i++) {
changeNodeColor(node, Color.WHITE);
Thread.sleep(500);
changeNodeColor(node, origColor);
Thread.sleep(500);
}
return 1;
}
}
提前致谢
Possible Duplicate:
How do I wait for a SwingWorker's doInBackground() method?
I've read that its really bad practice to do this but I think its the best way for me to achieve my goal...
Is there a way to block the main thread until the swing worker has finished in the following example?
public void flashNode(Node node, int noOfFlashes) {
GraphUpdater updater = new GraphUpdater(node, noOfFlashes);
updater.execute();
}
and the SwingWorker
class
public class GraphUpdater extends SwingWorker<Integer, Integer> {
Node node;
int noOfFlashes;
public GraphUpdater(Node n, int noFlashes) {
node = n;
noOfFlashes = noFlashes;
}
@Override
protected Integer doInBackground() throws Exception {
Color origColor = node.getColor();
for (int i=0; i<noOfFlashes; i++) {
changeNodeColor(node, Color.WHITE);
Thread.sleep(500);
changeNodeColor(node, origColor);
Thread.sleep(500);
}
return 1;
}
}
Thanks in advance
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
正如我所提到的,在 Swing EDT 期间切勿使用 Thread#sleep(int) ,GUI 会简单冻结直到 Thread#sleep(int) 结束,更多信息请参见 Swing 中的并发,关于冻结的示例 这里
您有三个(也许四个)选项如何在某个时间段更新 GUI 或延迟每次执行
使用 javax.swing.Timer
使用 SwingWorker
使用
Runnable#Thread
将所有内容放在一起 此处(加上
java.util.Timer
并将执行封装到invokeLater
中)as I mentioned, never use
Thread#sleep(int)
during Swing EDT, GUI simple freeze untilThread#sleep(int)
ends, more in the Concurency in Swing, example about freeze hereyou have three (maybe four) options how to update GUI on some period or to delay per time some execution(s)
use javax.swing.Timer
use SwingWorker
use
Runnable#Thread
put all together here (plus
java.util.Timer
with executions wrapped intoinvokeLater
)如果你想阻止,那么就不要使用摇摆工人,只需
在 EDT 上进行即可。 SwingWorker 的全部目的是不阻止 EDT。
如果您只想以一定的时间间隔更改组件的颜色(即闪烁组件),那么 javax.swing.Timer 可能更合适。
If you want to block, then don't use a swing worker, just do
on the EDT. SwingWorker's whole purpose is to not block the EDT.
If you just want to change the color of a component at certain intervals (i.e. flash the component) then a
javax.swing.Timer
might be more appropriate.