你需要做的工作在一個單獨的線程,並隨着工作的進展更新進度條的模型。
它在Swing事件線程,它可以通過與SwingUtilities.invokeLater
執行更新代碼來實現執行模式的更新是非常重要的。
例如:
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
}
}
}
的可能的複製[JProgressBar的,而在擺動數據加載](https://stackoverflow.com/questions/13366801/jprogressbar-while-data-loading-in-swing) –
@NisheshPratap這沒有幫助,我不明白那個人想要做什麼。 –