I am executing an operation that may take a long time and I want to limit it to 30 seconds. I am using a JProgressBar to show progres every second. The problem is that the JProgressBar doesn't show progress. My code is:
Your help will be greatly appreciated,
You might consider basing your code on the example from the tutorial: How to Use Progress Bars. In particular pay attention to this sentence which is hidden about a third of the way through:
Using a background thread instead of the event-dispatching thread prevents the user interface from freezing while the task is running.
Joined: Aug 01, 2005
Thank you Paul. I tried to base my code on How to Use Progress Bars; if I am making a mistake please tell me. I changed my code to run with SwingUtilities.invokeLater by I still get the same result; the progress bar displays 0%, does nothing until the end of the process and then displays 97%.
My code is running in parallel with the thread and it prints the values 1, 2, 3 ... which are set on the progress bar. The question is why is the progress bar not showing the values that I set?
To verify that the thread is not the problem I ran the same code commenting out the line that starts the thread and got the same results.
Anther mystery is that at the end the progress bar shows 97% (although the last value printed is 30), but if I set the first value to 30 it displays 100%.
I suggest you take a look at SwingWorker. A quick attempt to modify your code to use SwingWorker:
A little explanation:
SwingWorker executes doInBackground in its own thread which starts when you call execute(). In this thread you can call publish. Anything passed to publish will be sent to the process method, which is executed on the EDT. When doInBackground is done it calls done() on the EDT.
In this case I don't care about any values published, it's the number of publishes I care about; each published item should increase the progress bar value by one. That's why I used Void as the generic type; that basically means you cannot give it any value except null, since Void cannot be instantiated. I could just as well have used String.
One warning about the publish and process methods: even though you publish one element at a time, the SwingWorker can store a few before sending these all to the process method. In this case the List does not have to have one single null element, it can have many.
Thanks again. I found the error. I should use publish(new Object());
Thank you for your excellent idea. I had problems using "Void", so I implemented the code with "Object" as shown below. However, for some ungodly reason it is executing the done method before it ends doInBackground(); it just prints the first value of i (0). I don't know what I am doing wrong.