I've got a progress bar, when I strike the button, on the button listener I've got a progress bar that updates as something downloads. However, the GUI freezes until the download is complete. How can I get this progress bar to update as the download continues? However, if the download starts when the application is compiled without user interference, the download progresses as the progress bar updates. However, it's the complete opposite on JButton action listener.
How can I use SwingWorker to get this to work?
while((i=in.read(data,0,1024))>=0)
{
totalDataRead=totalDataRead+i;
bout.write(data,0,i);
float Percent=(totalDataRead*100)/filesize;
currentProgress.setValue((int)Percent);
float allP = Percent / 5;
all.setValue((int)allP);
}
This is only the loop (without catchException), how can I possibly get the GUI to update as it downloads, after the button listener?!
Execute the download in another thread using
SwingWorker
. Here you have a complete example i really like withprogressBar
, see setProgress() publish() and process(). When you usesetProgress()
it's a bound property you can take approach of observer pattern you can register a listener, then when this method is called gets fired and you catch and can update yourprogressBar
and also you decouple components.Example:
and in client code: