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

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

package test.dxc;

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

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JTextField;
import javax.swing.border.TitledBorder;

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

public class CopyFile extends JFrame implements ActionListener ... {

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

}

}

}

}

你可能感兴趣的:(ProgressBar)