Preface:
在使用 Java Swing 開發 UI 程式時, 有時候需要進行耗時工作時, 可以使用 Progress bar 提示使用者目前工作進度或是告訴使用者目前程式的工作狀態.
Demo Code:
下面代碼執行會開啟一個 UI, 並在上面顯示 Progress bar. 在背景使用 SwingWorker (類別 UpdateWorker) 動態的更新 Progress bar 的進度條:
當進度條上的數字達到 100, 則 SwingWorker 方法 done() 會被執行並關閉 UI 與結束程式.
Implementation:
- package swing.demo;
- import java.awt.BorderLayout;
- import java.awt.Container;
- import java.util.Random;
- import javax.swing.BorderFactory;
- import javax.swing.JFrame;
- import javax.swing.JProgressBar;
- import javax.swing.SwingWorker;
- import javax.swing.border.Border;
- public class ProgressSample {
- public static void main(String args[]) {
- JFrame f = new JFrame("JProgressBar Sample");
- f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- Container content = f.getContentPane();
- JProgressBar progressBar = new JProgressBar();
- progressBar.setValue(0);
- progressBar.setStringPainted(true);
- Border border = BorderFactory.createTitledBorder("Reading...");
- progressBar.setBorder(border);
- content.add(progressBar, BorderLayout.NORTH);
- f.setSize(300, 100);
- f.setVisible(true);
- UpdateWorker updateWorker = new UpdateWorker(f, progressBar);
- updateWorker.execute();
- }
- public static class UpdateWorker extends SwingWorker
- {
- JProgressBar bar = null;
- JFrame f=null;
- public UpdateWorker(JFrame f, JProgressBar bar)
- {
- this.bar = bar;
- this.f = f;
- }
- @Override
- protected String doInBackground() throws Exception {
- Random rdm = new Random();
- int pv = 0;
- while(pv<100)
- {
- Thread.sleep(rdm.nextInt(500)+500);
- pv+=rdm.nextInt(5);
- bar.setValue(pv);
- }
- return null;
- }
- @Override
- protected void done()
- {
- f.setVisible(false);
- f.dispose();
- }
- }
- }
* The Java Tutorial > How to Use Progress Bars
* [ Java 代碼範本 ] SwingWorker Example