`
jiqimiao
  • 浏览: 57894 次
  • 性别: Icon_minigender_1
  • 来自: 常州
社区版块
存档分类
最新评论

进度条JProgressBar结合线程实现copy文件进度实例

 
阅读更多

进度条JProgressBar结合线程实现copy文件进度

packagetest.dxc;

importjava.awt.BorderLayout;
importjava.awt.GridLayout;
importjava.awt.event.ActionEvent;
importjava.awt.event.ActionListener;
importjava.io.BufferedInputStream;
importjava.io.BufferedOutputStream;
importjava.io.File;
importjava.io.FileInputStream;
importjava.io.FileOutputStream;

importjavax.swing.JButton;
importjavax.swing.JFrame;
importjavax.swing.JPanel;
importjavax.swing.JProgressBar;
importjavax.swing.JTextField;
importjavax.swing.border.TitledBorder;

/***//**
*
@author左杰
*
*/

publicclassCopyFileextendsJFrameimplementsActionListener...{

privatestaticfinallongserialVersionUID=3222640218122985119L;
privateJProgressBarjpb=newJProgressBar();
privateJButtonjbtCopy=newJButton("copy");
privateJTextFieldjtfFrom=newJTextField();
privateJTextFieldjtfTo=newJTextField();

publicCopyFile()...{
JPaneljPanel2
=newJPanel();
jPanel2.setLayout(
newBorderLayout());
jPanel2.setBorder(
newTitledBorder("From"));
jPanel2.add(jtfFrom,BorderLayout.CENTER);

JPaneljPanel3
=newJPanel();
jPanel3.setLayout(
newBorderLayout());
jPanel3.setBorder(
newTitledBorder("To"));
jPanel3.add(jtfTo,BorderLayout.CENTER);

JPaneljPanel1
=newJPanel();
jPanel1.setLayout(
newGridLayout(2,1));
jPanel1.add(jPanel2);
jPanel1.add(jPanel3);

JPaneljPanel4
=newJPanel();
jPanel4.add(jbtCopy);

this.getContentPane().add(jpb,BorderLayout.NORTH);
this.getContentPane().add(jPanel1,BorderLayout.CENTER);
this.getContentPane().add(jPanel4,BorderLayout.SOUTH);
jpb.setStringPainted(
true);
jbtCopy.addActionListener(
this);
}

publicvoidactionPerformed(ActionEvente)...{
newCopyFileThread().start();
}

publicstaticvoidmain(String[]args)...{
CopyFileframe
=newCopyFile();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle(
"copyfile");
frame.setSize(
400,180);
frame.setVisible(
true);
}

classCopyFileThreadextendsThread...{
privateintcurrentValue;
publicvoidrun()...{
BufferedInputStreamin
=null;
BufferedOutputStreamout
=null;
try...{
FileinFile
=newFile(jtfFrom.getText().trim());
in
=newBufferedInputStream(newFileInputStream(inFile));

FileoutFile
=newFile(jtfTo.getText().trim());
out
=newBufferedOutputStream(newFileOutputStream(outFile));

longtotalByes=in.available();

jpb.setValue(
0);
jpb.setMaximum(
100);

intr;
longbytesRead=0;
byte[]b=newbyte[10];
while((r=in.read(b,0,b.length))!=-1)...{
out.write(b,
0,r);
bytesRead
+=r;
currentValue
=(int)(bytesRead*100/totalByes);
jpb.setValue(currentValue);
}

}
catch(Exceptione)...{
e.printStackTrace();
}
finally...{
try...{
if(in!=null)...{
in.close();
}

if(out!=null)...{
out.close();
}

}
catch(Exceptione)...{
e.printStackTrace();
}

}

}

}

}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics