I need to find a way to use the Swing Timer with a progress bar. I tried using Thread.sleep(), but it crashed the app when I used it. Any ways to use the Swing Timer instead of the Sleep()?
public void piiEros(int dist)
{
Pii pii = new Pii();
pii.setVisible(true);
for(int pc = 0;100 > pc; pc++)
{
try {
Thread.sleep(dist/100);
} catch (InterruptedException ex) {
Logger.getLogger(Trav.class.getName()).log(Level.SEVERE, null, ex);
}
pii.pg.setValue(pc);
}
pii.dispose();
o.Eros();
}
NOTES: Pii is a class with th Progress Bar. Dist is the speed at which it loads. Trav is the class the method is in. Pc stands for %, how much is done is displyed on the bar. o.Eros opens anotherr GUI.
It's probably easier (in the long run) to use a
SwingWorker
. It supplies a number of useful methods for updating the UI (from the context of the Event Dispatching Thread) while allowing to continue executing in the background...The
SwingWorker
allows you to separate the logic. In thedoInBackground
method you can focus on that part of the code that needs to operate outside the EDT, you canpublish
updates back to the EDT andprocess
them separately. When it's alldone
you can clean up as required.SwingWorker
also provides a progress monitoring functionality, so, in your case, this would you wouldn't have to use thepublish
/process
portion of the API if you didn't want to. This would allow you to attach aPropertyChangeListener
to a the worker without the need to expose the progress bar to it. (But I did for the example)you can change your
piiEros
method in this way: