Search code examples
javaswingjframejprogressbar

Running a JFrame with a JProgressBar


public void myMethod {
   MyProgessBarFrame progFrame = new MyProgressBarFrame(); // this is a JFrame
   progFrame.setVisible(true); // show my JFrame loading

   // do some processing here while the progress bar is running
   // .....

   progFrame.setvisible(false); // hide my progress bar JFrame
} // end method myMethod

I have the code above. But when I run it, the do some processing section does not process until I close the progress bar JFrame.

How will I show my progress bar and tell Java to continue in the do processing section?


Solution

  • You've got a classic problem with concurrency and Swing. Your problem is that you're doing a long-running task on the main Swing thread, the EDT or Event Dispatch Thread, and this will lock the thread until the process is complete, preventing it from doing its tasks including interacting with the user and drawing GUI graphics.

    The solution is to do the long-running task in a background thread such as that given by a SwingWorker object. Then you can update the progressbar (if determinant) via the SwingWorker's publish/process pair. For more on this, please read this article on Concurrency in Swing.

    e.g.,

    public void myMethod() {
      final MyProgessBarFrame progFrame = new MyProgessBarFrame();
      new SwingWorker<Void, Void>() {
         protected Void doInBackground() throws Exception {
    
            // do some processing here while the progress bar is running
            // .....
            return null;
         };
    
         // this is called when the SwingWorker's doInBackground finishes
         protected void done() {
            progFrame.setVisible(false); // hide my progress bar JFrame
         };
      }.execute();
      progFrame.setVisible(true);
    }
    

    Also, if this is being displayed from another Swing component, then you should probably show a modal JDialog not a JFrame. This is why I called setVisible(true) on the window after the SwingWorker code -- so that if it is a modal dialog, it won't prevent the SwingWorker from being executed.