gpt4 book ai didi

java - 如何与计算并行/在另一个线程中重新绘制()我的 JPanel?

转载 作者:行者123 更新时间:2023-12-01 18:43:57 25 4
gpt4 key购买 nike

好吧,我有一个如下所述的算法,我想知道如何在单独的线程而不是事件调度线程中重新绘制:

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()

...因为每次都会创建一个新线程。我该如何从逻辑上做到这一点?

最佳答案

很简单,使用 SwingWorkerSwingWorker 具有用于发布长时间运行操作的结果并在 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com