0

I am a beginner in java .So please let me know how can i simultaneously run the progress bar and my application code together.In other words i want to make my progressbar to increment as long as my application code is doing some processing.Please elaborate it with code. What i think is that i have to add two threads simultaneously.One thread updating the progressbar thread but i am not sure whether its the right way or not. i have written this code for incrementing progress bar (hard coded)

       class ProgressMonitor implements Runnable {

    public void run() {
        jProgressBar1.setStringPainted(true);
        //run untill 100% complete
        while (progress < 100) {
            //update the progressbar
            jProgressBar1.setValue(++progress);
            jProgressBar1.repaint();
            try {

                //Sleep for .25 second
                Thread.sleep(250);
            } catch (InterruptedException ex) {
            }
        }

    }   
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Xara
  • 8,748
  • 16
  • 52
  • 82

3 Answers3

3

The problem is basically that the long running task blocks the Event Dispatch Thread that updates the GUI. One solution is to do the work in a SwingWorker.

An abstract class to perform lengthy GUI-interaction tasks in a background thread. ..

See also the Concurrency in Swing lesson of the tutorial for more details.

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
1

The solution is indeed to use a SwingWorker. If you want to use in in combination with a JProgressBar, I would recommend to take a look at the JProgressBar tutorial, which has an example using SwingWorker in combination with JProgressBar. Or you do a quick search on this site and find examples like this one

Community
  • 1
  • 1
Robin
  • 36,233
  • 5
  • 47
  • 99
0

You can learn more about this and SwingWorker in this topic:

Manage GUI and EDT in a multi-task application

Community
  • 1
  • 1
damson
  • 2,635
  • 3
  • 21
  • 29