You need to do the work in a separate thread and update the progress bar's model as the work progresses.
It is important to perform the model updates in the Swing event thread, which can be accomplished by executing the update code with SwingUtilities.invokeLater
.
For example:
public class Progress {
public static void main(String[] args) {
JFrame frame = new JFrame("Loading...");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JProgressBar progressBar = new JProgressBar(0, 100);
frame.add(progressBar);
frame.pack();
frame.setVisible(true);
// A callback function that updates progress in the Swing event thread
Consumer<Integer> progressCallback = percentComplete -> SwingUtilities.invokeLater(
() -> progressBar.setValue(percentComplete)
);
// Do some work in another thread
CompletableFuture.runAsync(() -> load(progressCallback));
}
// Example function that does some "work" and reports its progress to the caller
private static void load(Consumer<Integer> progressCallback) {
try {
for (int i = 0; i <= 100; i++) {
Thread.sleep(100);
// Update the progress bar with the percentage completion
progressCallback.accept(i);
}
} catch (InterruptedException e) {
// ignore
}
}
}