Search code examples
swinguser-interfaceprogress-barjprogressbar

Adding a indeterminate JProgressBar from an action listener


I want a indeterminate progress bar to pop up as soon as the user presses the "run" button and then close when the work to be done by the application is finished. I used NetBeans to develop the GUI. How should I go about it? The gui class extends JFrame. Here is the action listener for the run button:

public class GUI extends JFrame{
    // other methods and constructos....
private JProgressBar pb = new JProgressBar();
private void runButtonActionPerformed(java.awt.event.ActionEvent evt) {                                          


   pb.setIndeterminate(true);

   //other functions start...
   runButton.setEnabled(false);
    setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
   //....blah blah
}
}

How do I add the progressbar to my JFrame, and then remove it when my work is done? I do NOT want to use Swing Worker.


Solution

  • You do not want to use the SwingWorker but you will have to (or a similar mechanism). You cannot show a JProgressBar while you keep the Event Dispatch Thread (EDT) occupied with your calculations.

    You will have to move your calculations to a separate Thread to free the EDT. Then the EDT will be able to show a JProgressBar during the calculations, and remove it when they are finished.

    More information on this can be found in the 'Concurrency in Swing' tutorial. An example of a SwingWorker and a JProgressBar can be found here.