Streetboy
Streetboy

Reputation: 4401

What is the ways updating jProgressBar?

I need to update jProgressBar in method which read from file and do some operations. I tried to update progress bar by this method:

 public void progressUpdate(int percent) {
     System.out.println("Update = "+percent);
     synchronized (jMainProgressBar) {
         jMainProgressBar.setValue(percent);
     }
     SwingUtilities.invokeLater(
         new Runnable() {

             public void run() {
             jMainProgressBar.updateUI();
             jMainProgressBar.repaint();
             }
         });
 }

how ever this works only then when method is done. But if i continuously updating by this method then nothing happens.

Maybe some know how to improve this method?

It also would be nice for more suggestion Worker thread and else.

Upvotes: 1

Views: 3019

Answers (4)

Abhishek Singh
Abhishek Singh

Reputation: 21

Check this out

 Timer barTimer;
 barTimer=new Timer(100,new ActionListener()
    {
     public void actionPerformed(ActionEvent e)
       {
        barvalue++;
        if(barvalue>jProgressBar1.getMaximum())
            {
                /* 
                 * To stop progress bar when it reaches 100 just write barTime.stop() 
                 */
               barTimer.stop();
               barvalue=0;

     }
    else
    {
        int a=(int)jProgressBar1.getPercentComplete();
        jProgressBar1.setStringPainted(true);
        jProgressBar1.setValue(barvalue);

      }
   }
    });
    barTimer.start();

Check the code at this link http://java23s.blogspot.in/2015/10/how-to-implement-progress-bar-in-java.html

Upvotes: 0

Robin
Robin

Reputation: 36611

Based on the comments you provided (but not from the question!) you are performing heavy work on the Event Dispatch Thread (EDT). This blocks that thread and avoids any scheduled repaints to be performed. That is why you only see the update of your JProgressBar after the work is finished, as that is the moment the EDT becomes available to perform the repaint.

The solution is already provided in the links posted by others but it basically comes down to:

  • perform the work on a worker thread
  • update the progress on the JProgressBar on the EDT

The two most common ways to achieve this are using a SwingWorker or using SwingUtilities.invokeLater from the worker thread.

All relevant links can be found in the answer of Yohan Weerasinghe

Upvotes: 1

aioobe
aioobe

Reputation: 420921

You probably want to do

public void progressUpdate(final int percent) {
     SwingUtilities.invokeLater(new Runnable() {
         public void run() {
             jMainProgressBar.setValue(percent);
         }
     });
}

Upvotes: 3

Related Questions