文章目錄
- ProgressMonitorInputStream類繼承層次
- 構造方法
- 操作方法
- 範例程式碼
在讀取大型檔案或者其它大批量資料輸入操作時,希望能夠通過一個進度條顯示當前的進度,現在在Java中非常容易實現,僅僅需要幾行代碼即可。Java的swing包提供了ProgressMonitorInputStream類,該類提供了自動地彈出進度視窗和事件處理機制。使用這個類也非常方便,只需要把任何一個InputStream作為參數,構造一個新的ProgressMonitorInputStream類,其它不需要任何額外的代碼,即可實現進度視窗的自動產生。ProgressMonitorInputStream類可以和其它InputStream一樣使用。
ProgressMonitorInputStream類繼承層次
[pre]java.lang.Object
|
+--java.io.InputStream
|
+--java.io.FilterInputStream
|
+--javax.swing.ProgressMonitorInputStream[/pre]
構造方法
ProgressMonitorInputStream(Component parentComponent, Object message, InputStream in)
parentComponent - 觸發被監視操作的組件
message - (如果彈出進度顯示視窗),顯示在進度顯示視窗中的指示資訊
in - 需要監視的輸入資料流
操作方法
除了在InputStream和FilterInputStream中繼承的方法外,還增加了如下方法:
- 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方法。
範例程式碼
- import java.awt.FlowLayout;
- import java.awt.event.ActionEvent;
- import java.awt.event.ActionListener;
- import java.io.FileInputStream;
- import java.io.InputStream;
- import javax.swing.JButton;
- import javax.swing.JFrame;
- import javax.swing.ProgressMonitorInputStream;
- 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();
- }});
-
- // 設定預設的視窗關閉行為,並顯示視窗。
- f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- f.setVisible(true);
- }
- }