I am using CompletableFuture to run a long running operation. Meanwhile, i use SwingWorker to update a progress bar with increments of 5.
JProgressBar progressBar = new JProgressBar();
progressBar.setMinimum(0);
progressBar.setMaximum(100);
progressBar.setValue(0);
progressBar.setStringPainted(true);
CompletableFuture<NetworkToolsTableModel> completableFuture = CompletableFuture.supplyAsync(() -> asyncTask());
SwingWorker worker = new SwingWorker() {
@Override
protected Object doInBackground() throws Exception {
int val = 0;
while (!completableFuture.isDone()) {
if (val < 100) {
val += 5;
progressBar.setValue(val);
}
Rectangle bounds = progressBar.getBounds(null);
progressBar.paintImmediately(bounds);
}
return null;
}
};
worker.execute();
The progress bar doesn't update until the asynchronous method is finished. I have also tried doing this operation on the EDT thread, but to no avail. What you are seeing is basically me trying to just do trial and error at this point.
Why is the progress bar not updating? How can I fix this?
Stop and take a closer look at Worker Threads and SwingWorker.
A
SwingWorkeris meant to allow you to perform a long running task, which may produce intermediate results, and allow you topublishthose results back to the Event Dispatching Thread to be safely processed (via theprocessmethod).You "could"
publishthe progress updates and update the progress bar inprocessmethod, butSwingWorkeralready provides aprogressproperty, which you can monitor. Take a look at theSwingWorkerJavaDocs for a number of ready made examples!Run Example