FFF

FB留言板

CopyFile.java簡單的展示如何使用JProgressBar顯示檔案複製進度




/* @description: 簡單的展示如何使用JProgressBar顯示檔案複製進度
* @source: Introduction to Java Programming Sixth Edition,Y.DANIEL LIANG
* @chapter: MultiThreading, p.832
**/

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
import java.io.*;

public class CopyFile extends JFrame{
private JProgressBar progressBar = new JProgressBar();
private JButton btnCopy = new JButton("Copy");
private JTextField txtFrom = new JTextField();
private JTextField txtTo = new JTextField();

public CopyFile() {
//檔案來源
JPanel panelFrom = new JPanel();
panelFrom.setLayout(new BorderLayout());
panelFrom.setBorder(new TitledBorder("From"));
panelFrom.add(txtFrom, BorderLayout.CENTER);
//檔案目的
JPanel panelTo = new JPanel();
panelTo.setLayout(new BorderLayout());
panelTo.setBorder(new TitledBorder("To"));
panelTo.add(txtTo, BorderLayout.CENTER);
//放置容器
JPanel panelContainer = new JPanel();
panelContainer.setLayout(new GridLayout(2,1));
panelContainer.add(panelFrom);
panelContainer.add(panelTo);
//複製按鈕
JPanel panelCopy = new JPanel();
panelCopy.add(btnCopy);


this.add(progressBar , BorderLayout.NORTH);
this.add(panelContainer , BorderLayout.CENTER);
this.add(panelCopy , BorderLayout.SOUTH);

//設進度表百分比
progressBar.setStringPainted(true);

btnCopy.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
btnCopy.setEnabled(false);
new Thread(new CopyFileTask()).start();

}
});


}

public static void main(String args[]) {
CopyFile frame = new CopyFile();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("Copy File");
frame.setSize(400,180);
frame.setLocation(300,180);
frame.setResizable(false);
frame.setVisible(true);
}

//inner class
class CopyFileTask implements Runnable {
private int currentValue;
public void run() {
//負責輸入Stream
BufferedInputStream in = null;
//負責輸出Stream
BufferedOutputStream out = null;
try {
File inFile = new File(txtFrom.getText().trim());
in = new BufferedInputStream(new FileInputStream(inFile));

File outFile = new File(txtTo.getText().trim());
out = new BufferedOutputStream(new FileOutputStream(outFile));
//來源檔案總共讀取多少Bytes
long totalBytes = in.available();
//設置初始值與最大值
progressBar.setValue(0);
progressBar.setMaximum(100);
//複製來源檔案到目的檔案
int r ;
long byteRead = 0;
byte[] b = new byte[1024];
while((r = in.read(b,0,b.length)) != -1) {
out.write(b, 0 , r);
//累加讀取了多少Bytes,並且顯示在JProgressBar
byteRead += r;
currentValue = (int) (byteRead * 100 / totalBytes);
progressBar.setValue(currentValue);
}

}catch(FileNotFoundException fnfE) {
fnfE.printStackTrace();
}catch(IOException ioE) {
ioE.printStackTrace();
}finally {
btnCopy.setEnabled(true);
try {
if( in != null) in.close();
if(out != null) out.close();

}catch(Exception ex) {}
}
}
}

}

0 comments: