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(); }});