频道直达 - 专题 - 新闻 - 技巧 - 组网 - 开发 - 安全 - web编程 - 图像 - 操作系统 - 数据库 - 教育 - 旅游 - 健康 - 时尚 - 驱动 - 软件 - 游戏 - 多媒体 - ERP - 讨论组

ProgressMonitorInputStream类的使用(笔记)

来源: 作者: 出处:巧巧读书 2006-10-12 进入讨论组

  在写GUI程序时,常常需要读取一些比较大的文件,此时可能需要几分钟的时间。我们希望界面尽量友好,使用户随时知道读取文件、处理的进度。在大多数Windows程序中,大家对进度条都已经非常熟悉,Java中也有现成的类可以非常方便地完成此项功能--ProgressMonitorInputStream。
下面是一个小的程序,你可以编译运行。运行后点击窗口中的“Press me”按钮,将弹出一个窗口,其中包含一个进度条,显示读取当前目录中名为bigfile.dat的文件的进度。还包含一个“取消”按钮,可以随时中止读取线程。

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 Test { public static void main(String[] args) { // create a test frame with a "press me" button final JFrame f = new JFrame("Sample"); f.getContentPane().setLayout(new FlowLayout()); JButton b = new JButton("Press me"); f.getContentPane().add(b); f.pack(); // set up the file read action b.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // when button is pressed, start a new thread // to read the file. A new thread is needed because we // need to free the GUI update thread to paint the // progress monitor new Thread() { public void run() { try { // open the file, wrapping it in a ProgressMonitorInputStream InputStream in = new FileInputStream("bigfile.dat"); ProgressMonitorInputStream pm = new ProgressMonitorInputStream(f,"Reading the big file",in); // read the file. If it´s taking too long, the progress // monitor will appear. The amount of time is roughly // 1/100th of the estimated read time (based on how long // it took to read the first 1/100th of the file.) // Note that by default, the dialog won´t appear unless // the overall estimate is over 2 seconds. int c; while((c=pm.read()) != -1) { // do something } pm.close(); // needs better error handling, of course... } catch(Exception ex) { ex.printStackTrace(); } } }.start(); }}); // display the frame f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setVisible(true); }}通告:http://www.qqread.com/java/2006/10/c218587.html进入讨论组讨论。
更多专题 【深 度 阅 读】 相 关 文 章
收藏此文】【 】【打印】【关闭
相关图文阅读
频道图文推荐
健 康 咨 询
时 尚 咨 询
巧巧读书宗旨
相关专题
最新论坛文章
站内各频道最新更新文档
站内最新制作专题
热门关键字导读
Photoshop教 程照片处理 照片制作 PS快捷键 抠图
计 算 机 故 障XP系统修复
艺 术 与 设 计设计 流媒体 设计欣赏 边框
计 算 机 安 全ARP
站内频道文章精选
巧巧电脑频道编辑信箱  告诉我们您想看的专题或文章