As @happyburnout has pointed out, you'd be better of processing you download in a separate thread, using a SwingWorker is probably the best solution for what you are doing.
The main reason is you're blocking the Event Dispatching Thread (AKA EDT) from running, preventing any repaint requests (and other UI important things) from been processed.
You should have a read through
Now this is taken almost directly from the API docs, but gives a basic idea of a SwingWoker
with a JProgressBar
The "Worker"...
public class Worker extends SwingWorker<Object, Object> {
@Override
protected Object doInBackground() throws Exception {
// The download code would go here...
for (int index = 0; index < 1000; index++) {
int progress = Math.round(((float)index / 1000f) * 100f);
setProgress(progress);
Thread.sleep(10);
}
// You could return the down load file if you wanted...
return null;
}
The "progress pane"
public class ProgressPane extends JPanel {
private JProgressBar progressBar;
public ProgressPane() {
setLayout(new GridBagLayout());
progressBar = new JProgressBar();
add(progressBar);
}
public void doWork() {
Worker worker = new Worker();
worker.addPropertyChangeListener(new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
if ("progress".equals(evt.getPropertyName())) {
progressBar.setValue((Integer) evt.getNewValue());
}
}
});
worker.execute();
}
}
Remember the golden rules of Swing
- Never, never, never update a UI component from any
Thread
other then the EDT
- Always perform time consuming tasks on a different
Thread
- (Something, something, something about layout managers - that's more of a personal thing ;))
And you will have a happy and easy time with Swing :D
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…