ProgressMonitor getProgressMonitor() //得到當前對象使用的ProgressMonitor對象。 int read() int read(byte[] b) int read(byte[] b, int off, int len) void reset() long skip(long n) //上面幾個方法都是覆蓋了FilterInputStream中的方法, 因為需要更新進度指示。 void close() //因為需要關閉進度監視對象和窗口, 所以覆蓋了FilterInputStream父類中的close方法。
public class ProgressMonitorTest { public static void main(String[] args) { // 創建一個包含“Click me”的窗口 final JFrame f = new JFrame("ProgressMonitor Sample"); f.getContentPane().setLayout(new FlowLayout()); JButton b = new JButton("Click me"); f.getContentPane().add(b); f.pack();
// 設置按鈕的動作事件 b.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // 這兒使用了新的線程處理按鈕的動作事件, 因為我們需要 //主窗口的線程響應用戶。這樣你可以多次點擊該按鈕, //會啟動多個讀取文件的線程。主窗口也保持響應。 new Thread() { public void run() { try { // 打開文件輸出流,
把InputStream包裝在ProgressMonitorInputStream中。 //在當前目錄中需要放置一個大文件,建議超過50M InputStream in = new FileInputStream("bigfile.dat"); ProgressMonitorInputStream pm = new ProgressMonitorInputStream(f,"Reading a big file",in); // 讀取文件,假如總耗時超過2秒, 將會自動彈出一個進度監視窗口。 // 顯示已讀取的百分比。 int c; while((c=pm.read()) != -1) { // 處理代碼 } pm.close(); } catch(Exception ex) { ex.printStackTrace(); } } }.start(); }});