Search This Blog

Problem With JProgressBar setValue Method? JProgressBar Value Not Updating - Solution

I had a problem with a JProgressBar. I called setValue() method of the java swing class JProgressBar for an object but the JProgressBar is still sowing zero progress.This problem may occur for many people. People use the words:

Jprogressbar setvalue not upadting
jprogressbar.setvalue not working
jprogressbar setvalue problem

for googling this problem. All these keyword combinations have a presumption that the problem is with java not on our part, Actually, the problem is on our part but it is a silly mistake. I know two reasons for such problem.


Reason 1

This was the problem i encountered. You did not set the value correctly. Actually you set the value to zero and therefore JProgressBar shows zero progress. I will explain with a simple example. Suppose i am downloading a file from internet in java and i want to show the progress in a JProgressBar object named myprogressbar. downloaded and filesize are integers,
while((len=is.read(buf))>0)             {                 downloaded+=len;                 fo.write(buf,0, len);                 myprogressbar.setValue(downloaded/filesize*100);             }

The above code will always set the myprogressbar's value to zero. Since always downloaded<filesize, downloaded/filesize will always be less than 1 and therefore will be rounded to zero as integer. Whatever value you multiple with zero, you will get zero itself. So, just rewrite the line of code as:

myprogressbar.setValue(downloaded*100/filesize);

You shall display the value downloaded/filesize*100 to see that it is zero. Change the code such that, divisions are done after mltiplication.

Reason 2

In my above code, i have written the loop that sets the value of JProgressBar in a separate thread. If you are setting the value of JProgressBar from within a loop, It should be done using a separate thread. Event Dispatch Thread (EDT) is responsible for many tasks related to swing components. If you use a long loop inside the Event Dispatch thread, it will become busy and unable to bring about necessary changes in the swing components. So, use a  separate thread to execute the loop.

No comments:

Post a Comment