问题
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?!
回答1:
Execute the download in another thread using SwingWorker
. Here you have a complete example i really like with progressBar
, see setProgress() publish() and process(). When you use setProgress()
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 your progressBar
and also you decouple components.
Example:
public class MyWorker extends SwingWorker<Integer, String> {
@Override
protected Integer doInBackground() throws Exception {
// Start
publish("Start Download");
setProgress(1);
// More work was done
publish("More work was done");
setProgress(10);
// Complete
publish("Complete");
setProgress(100);
return 1;
}
@Override
protected void process(List< String> chunks) {
// Messages received from the doInBackground() (when invoking the publish() method)
}
}
and in client code:
SwingWorker worker = new MyWorker();
worker.addPropertyChangeListener(new MyProgressListener());
worker.execute();
class MyProgressListener implements PropertyChangeListener {
@Override
public void propertyChange(final PropertyChangeEvent event) {
if(event.getPropertyName().equalsIgnoreCase("progress")) {
downloadProgressBar.setIndeterminate(false);
downloadProgressBar.setValue((Integer) event.getNewValue());
}
}
}
回答2:
SwingWorker is the way to do it: http://java.dzone.com/articles/multi-threading-java-swing but, it's quite tricky to use it.
Another option is a very small framework called Foxtrot: http://foxtrot.sourceforge.net/docs/
来源:https://stackoverflow.com/questions/18563028/jbutton-action-listener-progress-bar-update-without-freezing