2017-07-19 63 views
2

我在这里阅读了有关Swing并发的知识Concurrency in Swing但我不明白在哪里执行我的工作线程在我的项目中 我有一个面板描绘了它的组件,如果有东西被点击。面板类似乎是这样的。点击鼠标后,我们调用board方法callAI();我应该在哪里放置工作线程

public class BoardPanel extend JPanel implements MouseListener , MouseMotionListener 
{ 
    private Board myBoard; 

    public BoardPanel() 
    { 
     //////////// Some code here 
    } 

    public void paintComponent(Graphics g) 
    { 
     ///Some code here 
    } 

    public void mouseClicked(MouseEvent event) 
    { 
     ///Some changes in the panel components. 
     repaint(); 
     myBoard.callAI(); 
    } 
} 

板类实现如下。在callAI()方法中,调用类AIPlayer的对象播放器的方法startThinking()。这是消耗CPU并在方法startThinking()完成后使面板冻结并重新绘制的方法。

public class Board 
{ 
    private AIPlayer player; 

    public Board() 
    { 
     //some code here. 
    } 

    public void callAI() 
    { 
     player.startThinking(); 
    } 

} 

正如我从我读到的理解我需要使用工作线程。但我不明白我应该在哪个班级使用它。我认为它与Swing组件有关,所以我需要在BoardPanel类中使用它,但是我不能扩展SwingWorker类,因为我已经扩展了JPanel。我应该使用BoardPanel类中的任何匿名类吗? 所以我的问题是,我应该在哪里扩展SwingWorker类并使用doInBackground()方法以及为什么。

回答

1

你可以使用匿名的SwingWorker的startThinking方法

startThinking() {  
     new SwingWorker<Void, Void>() { 
       @Override 
       public Void doInBackground() { 
        // do your work here 

        return null; 
       } 
     }.execute(); 
    } 

你想要做的任何一种繁重的工作在另一个线程Swing应用程序的内部。你甚至可以专用另一个扩展SwingWorker的类来调用,并在startThinking方法中执行。 希望这会让你走向正确的方向!

+1

是的,这是正确的方向,谢谢 –