编写程序,实现读取文件时候出现一个表示进度的进度条。我写的程序是这样的但是在eclipse中,按钮的监听事件不能执行。这是怎么回事。代码如下:
package jindutiao;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.InputStream;
public class JinDu extends JFrame {
private JFrame jf=new JFrame("进度");
private Container co=jf.getContentPane();
private JButton openbutton=new JButton("读取文件");
private JPanel jp=new JPanel();
public JTextArea jt=new JTextArea();
//private ProgressMonitorInputStream pmi=new ProgressMonitorInputStream(parentComponent, message, in);
JinDu() {
File file=new File("Data.txt");
if(file.exists()){
file.delete();
}else{
try{
file.createNewFile();
}catch(Exception e){
e.printStackTrace();
}
}
try{ FileOutputStream out=new FileOutputStream(file);
byte buy[]="jhfjfhjhfsdjhfkbsdgfuhjbhdsbasdgfhsdfggfhdsgfhbdsfjksdhfashfsdhfuehfdshfushhdsghffhgfuyegf".getBytes();
//+" hfjdfjsnfjsdhfjsnfjashfsdnfjsdhfjsdafhsjdsahnfjnjasfjiesajfkljhfoiesjfiowerfi".getBytes();
out.write(buy);
out.close();}catch(Exception e2){
e2.printStackTrace();
}
jf.setVisible(true);
jf.setSize(200, 250);
jf.setDefaultCloseOperation(jf.EXIT_ON_CLOSE);
//co.setLayout(new GridLayout(2, 1, 10, 10));
jp.add(openbutton);
co.add(jp);
openbutton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try{
FileInputStream in=new FileInputStream(file);
byte byt[]=new byte[5000];
int len=in.read(byt);
//jt.setText(new String(byt,0,len));
ProgressMonitorInputStream pmi=new ProgressMonitorInputStream(jf, "Loding",in);
ProgressMonitor progressMonitor = pmi.getProgressMonitor();
int read_unit = 2;// 设置每次读取的字节数
int all = pmi.available();// 得到目标文件的总字节数
int readed = 0;// 每次实际读取到的字节数
byte[] data = new byte[read_unit];// 字节数组,保存读取到的字节数
while (pmi.available() > 0) {
Thread.sleep(1);// 故意放慢速度好看清进度条
int into = pmi.read(data);
readed += into;
// System.out.write(data);
float process = (float) readed / all * 100;// 算出百分比
// System.out.println("archived " + process + " %");
progressMonitor.setNote("archived " + process + " %");// 显示在进度条上
}
in.close();
}catch(Exception e1){
e1.printStackTrace();
}
// TODO 自动生成的方法存根
}
});
// TODO 自动生成的方法存根
}
// TODO 自动生成的构造函数存根
public static void main(String[] args) {
new JinDu();
// TODO 自动生成的方法存根
}
}