The JLabel
and JProgressBar
do not change their value, only when the method ends.
this.desSave.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
DownloadXml();
}
});
private void DownloadXml() throws Exception {
Integer a = 456;
int value = (1000 / a) - 1;
this.numDes.setText("0" + "/" + a);
for (int i = 0; i < a; i++) {
saveXml(ligas.get(i),i,path);
this.numDes.setText(i + "/" + a); //this is a jlabel
this.progressbar.setValue(value * i); //jprogressbar
}
}
private void SaveXml(String xml,int a,String path) throws IOException {
}
You're blocking the event dispatch thread, which is preventing it from updating the UI. You could use a Thread
, but Swing is a single threaded API, meaning that updates should only be made to UI from within the context of the event dispatching thread.
You could use a SwingWorker
, which will allow you to execute your long running process in a background thread, but which has support for synchronising updates to the UI safely.
Together with its progress
and PropertyChange
support, it becomes easy to manage, for example.
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();
}
}
You can use the publish
/process
support to and updates to the EDT, the PropertyChange
support or the worker's done method to get the result of the worker when it's done safely, from within the EDT