作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
好吧,我有一个如下所述的算法,我想知道如何在单独的线程而不是事件调度线程中重新绘制:
Input an ArrayList of 2 Dimensional Point objects.
while(each point object has not been a starting point)
LOOP
Arbitrarily choose a starting point
Find the shortest path through all nodes
Call repaint() on the JPanel that displays this path.
END LOOP
我的问题是,如何设置另一个线程,以便每次计算最短路径时,它将路径发送到重新绘制 JPanel 的线程?我想这样做是因为我觉得我在浪费时间重新绘制(),这可以使该方法更快。
我猜我不能简单地说:
new Thread() {
void run() {
myJPane.repaint();
}
}.start()
...因为每次都会创建一个新线程。我该如何从逻辑上做到这一点?
最佳答案
很简单,使用 SwingWorker
。 SwingWorker
具有用于发布长时间运行操作的结果并在 EDT 上处理这些结果的方法。
所以基本上...
public class PathFinderWorker extends SwingWorker<Void, Path> {
protected Void doInBackground() throws Exception {
Input an ArrayList of 2 Dimensional Point objects.
while(each point object has not been a starting point)
LOOP
Arbitrarily choose a starting point
Find the shortest path through all nodes
publish(path);
END LOOP
}
protected void process(List<Path> paths) {
// Process the results as required...
}
}
关于repaint
的有趣之处在于,根据其设计,它是少数实际上线程安全的方法之一。
也就是说,repaint
要求 RepaintManager
重新绘制给定区域。 RepaintManager
将在不久的将来的某个时间将一个 paint
事件安排到事件队列中,然后由事件调度线程安全地进行处理。 .
更多详情,请查看Concurrency in Swing
关于java - 如何与计算并行/在另一个线程中重新绘制()我的 JPanel?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18695808/
我是一名优秀的程序员,十分优秀!