Xara
Xara

Reputation: 9118

Java progress bar to work simultaneously work with application code

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) {
            }
        }

    }   

Upvotes: 0

Views: 4834

Answers (3)

Robin
Robin

Reputation: 36621

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

Upvotes: 1

damson
damson

Reputation: 2645

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

Manage GUI and EDT in a multi-task application

Upvotes: 0

Andrew Thompson
Andrew Thompson

Reputation: 168845

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.

Upvotes: 3

Related Questions