Joan Plepi
Joan Plepi

Reputation: 500

where should I put the worker thread

I read about Swing concurrency here Concurrency in Swing but I do not understand where to execute my worker thread in my project I have a panel which paints it component , which call a method from another object in case if something is clicked. The panel class seems something like that. After mouse clicked we call the board method 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();
    }
}

The board class is implemented like below. THe callAI() method , make a call of the method startThinking() of the object player of class AIPlayer. This is the method that consumes CPU and make the panel freeze and repaint after the method startThinking() has finished.

public class Board
{
    private AIPlayer player;

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

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

}

As I understood from what I read I need to use the worker thread. But I do not understand in which class should I use it. I thought it has to do with Swing components so I need to use it in BoardPanel class , but I cant extend the SwingWorker class because I have already extend JPanel. Should I use any anonymous class inside BoardPanel class ? So my question is , where should I extend the SwingWorker class and use doInBackground() method and why.

Upvotes: 3

Views: 103

Answers (1)

BaneDad
BaneDad

Reputation: 157

You could use an anonymous SwingWorker inside of the startThinking method

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

                    return null;
                }
        }.execute();
    }

You want to do any kind of heavy lifting in a Swing application in another Thread. You could even dedicate another class that extends SwingWorker to call, and execute inside of the startThinking method. Hope this leads you in the right direction!

Upvotes: 2

Related Questions