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

    }   

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

0

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

Manage GUI and EDT in a multi-task application

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.