搜索算法(DFS,BFS,A star等)。如何在没有“冻结”的情况下更新GUI(具有更新状态)?

时间:2012-03-26 18:36:02

标签: java search 8-puzzle

我的问题很简单。

假设我正在执行算法“A star”(使用启发式函数搜索算法来计算下一个要访问的状态)。

我想在网格中显示更新(我会将其应用于8-puzzle问题)。我该怎么办?我希望变化清晰可见..但根据我的经验,如果我只是执行类似Grid[6].showValue(newValue)的操作,GUI将只是“待命”。

我确信这可以通过多线程完成(也许?),但是有更简单的方法吗?

如果可能的话还有一个非常简单的问题: 我想知道在Java(我的IDE是Netbeans)中是否有任何类包含搜索方法,如BFS,DFS和A star?如果是这样,你能提供一个算法代码的链接(我需要使用它们作为我的代码的基础..我不能直接包括它们..你知道..大学任务)。我想这个代码很容易找到,因为Java是一种开源语言。我错了吗?

非常感谢

2 个答案:

答案 0 :(得分:3)

不要在GUI线程中进行处理。

如果我们在这里谈论,那就是事件派遣线程;使用Concurrency in Swing tutorial中描述的工作线程。

答案 1 :(得分:1)

您应该在单独的线程中进行处理,如MДΓΓБДLL建议的那样。基本上,您必须在实现Runnable的类中实现与搜索相关的代码,该类“标记”类在线程中可执行。

为此,您可以使用SwingWorker

SwingWorker<Integer[], Void> worker = new SwingWorker<Integer[], Void>() {
    public Integer[] doInBackground() {
        //do the computation here. This will be executed in a different thread; 
        //thus allowing the event dispatch thread (=GUI thread) to ensure responsiveness of the UI.
        //NEVER update your GUI here since this could cause strange errors that are sometimes hard to track down.
    }
    public void done() {
        try {
            Integer[] result = get(); //this is executed in the GUI thread after 
            //execution if the doInBackground method finished and fetches the result of 
            //that method. You should update your GUI here.
        } catch (InterruptedException ex) {
            ex.printStackTrace();
        } catch (ExecutionException ex) {
            ex.printStackTrace();
        }
   }
}

对于你的第二个答案:以一种通用的方式实现算法相当困难,以至于它可用于不同的数据类型,特别是因为你使用BFS,DFS和A-Star的树可能包含任何类型的数据。我认为你应该在教科书或讲座节点中找到伪代码的算法;如果没有,请在某处查找并尝试自己实施。

相关问题