服务热线:13616026886

技术文档 欢迎使用技术文档,我们为你提供从新手到专业开发者的所有资源,你也可以通过它日益精进

位置:首页 > 技术文档 > JAVA > 新手入门 > 基础入门 > 查看文档

progressmonitorinputstream类的使用(笔记)


  在写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); }}

扫描关注微信公众号