Search code examples
javamultithreadingswingswingworker

Start another thread after SwingWorker completes in Java


I know there many questions on SO but non of them has good enough answer and before asking here I googled a lot specially SO but nothing could make it clear. I just simply wants to start my other thread when my SwingWorker finish its work.

I want to start a timer when the SwingWorker finishes it's work but cannot figure out how.

class createGUI extends SwingWorker<Void, Void>
{
    @Override
    protected Integer doInBackground() throws Exception
    {
         //Some long processing
    }

    @Override
    protected void done()
    {
         //Doing GUI work here
         prgBar.setInderminent(false);
    }
}

//Starts a progressBar and calls createGUI();
prgBar.setInderminent(true);
new createGUI().execute();

Now there is another startTimer Thread which I want to start when this SwingWork finishes.

public class startTimer implements Runnable
{
     @Override
     public void run()
     {
         while(true)
         {
             Thread.sleep(1000);
             //Update Database
         }
     }
}

But I don't understand how can I do so?


Solution

  • Unless I'm missing something, you could pass a reference in the constructor to createGUI and start that when done().

    class createGUI extends SwingWorker<Void, Void>
    {
      private Thread startTimer;
      public createGUI(Thread startTimer) {
        this.startTimer = startTimer;
      }
      @Override
      protected Integer doInBackground() throws Exception {
         //Some long processing
      }
    
      @Override
      protected void done()
      {
         //Doing GUI work here
         prgBar.setInderminent(false);
         startTimer.start();
      }
    }
    

    You would also need to change

    new createGUI().execute();
    

    to something like

    new createGUI(new Thread(new startTimer())).execute();
    

    Also, class names should start with a capital letter. CreateGUI and StartTimer