【发布时间】:2013-12-26 02:47:20
【问题描述】:
在使用 SwingWorker 时,我的 JScrollPane/JTextArea 出现了一些问题。这是我目前拥有的:
JTextArea txtDirs;
Task task;
//EDT
public void createGUI(){
txtDirs = new JTextArea();
txtDirs.setBounds(10, 56, 414, 125);
txtDirs.setEditable(false);
contentPane.add(new JScrollPane(txtDirs));
task = new Task();
task.execute();
}
class Task extends SwingWorker<Void, Void>{
@Override
public void doInBackground(){
for(file : files){
txtDirs.append(file.getAbsolutePath);
}
}
@Override
public void done(){
closeWindow();
}
}
这不是确切的代码,但它应该给你它的要点。无论如何,问题是 JScrollPane 根本没有出现,尽管 doInBackground() 方法中的代码确实运行了。我希望它与在后台任务中更新(txtDirs.append(file.getAbsolutePath()))有关。但是,我不太确定如何使它在这种情况下工作。该框架按预期显示,但它完全是空白的。 Task 类中应该有一个“进程”方法吗?那是应该放置“txtDirs.append(file.getAbsolutePath())”的地方吗?恐怕我对 SwingWorkers 的使用还比较陌生,因此我们将不胜感激。
编辑:
经过一番困惑后,我决定只发布我的完整代码。我知道它有问题,而且我可能误解了 cmets 中提到的一些内容,所以我希望发布此内容能让有人指出我犯的任何明显错误。
完整代码:
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JButton;
import javax.swing.JProgressBar;
import javax.swing.JLabel;
import javax.swing.SwingWorker;
import org.apache.commons.io.FileUtils;
@SuppressWarnings("serial")
public class BasicCopy extends JFrame {
private JPanel contentPane;
private JTextArea txtCopiedDirs;
private JButton btnCancel;
private JProgressBar progressBar;
private JLabel lblCopying;
private String mainDrive;
private String backupDrive;
private String username;
private String backupDir;
long totalSize = 0L; //total size of directories/files
long currentSize = 0L; //current size of files counting up to ONE_PERCENT
long currentPercent = 0L; //current progress in %
long ONE_PERCENT; //totalSize / 100
Task task;
public BasicCopy() {
}
public BasicCopy(String inDrive, String outDrive, String username, long space){
mainDrive = inDrive;
backupDrive = outDrive;
this.username = username;
totalSize = space*1048576;
ONE_PERCENT = totalSize/100;
createGUI();
}
public void createGUI(){
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("Backup Progress");
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
txtCopiedDirs = new JTextArea(10, 50);
txtCopiedDirs.setEditable(false);
contentPane.add(new JScrollPane(txtCopiedDirs));
btnCancel = new JButton("Cancel");
btnCancel.setBounds(169, 227, 89, 23);
btnCancel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
closeWindow();
}
});
contentPane.add(btnCancel);
progressBar = new JProgressBar(0, 100);
progressBar.setBounds(10, 192, 414, 24);
progressBar.setValue(0);
contentPane.add(progressBar);
lblCopying = new JLabel("Now backing up your files....");
lblCopying.setBounds(10, 11, 157, 34);
contentPane.add(lblCopying);
setVisible(true);
task = new Task();
task.execute();
}
/**
* Swing Worker class
*/
class Task extends SwingWorker<Void, String>{
@Override
public Void doInBackground(){
setProgress(0);
//Create Backup Directory
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("MM-dd-yyyy_HMMSS");
String timestamp = sdf.format(date);
backupDir = backupDrive + ":\\" + "Backup_" + timestamp;
File backupDirectory = new File(backupDir);
backupDirectory.mkdir();
//Copy Files
//Main directories
String pics = mainDrive + ":\\Users\\" + username + "\\Pictures\\";
String docs = mainDrive + ":\\Users\\" + username + "\\Documents\\";
String vids = mainDrive + ":\\Users\\" + username + "\\Videos\\";
String musc = mainDrive + ":\\Users\\" + username + "\\Music\\";
//Backup directories
String bkPics = backupDir + "\\Pictures\\";
String bkDocs = backupDir + "\\Documents\\";
String bkVids = backupDir + "\\Documents\\";
String bkMusc = backupDir + "\\Pictures\\";
String[] directories = {pics, docs, vids, musc};
String[] bkDirectories = {bkPics, bkDocs, bkVids, bkMusc};
//Loop through directories and copy files
for (int i = 0; i < directories.length; i++){
File dir = new File(directories[i]);
File dest = new File(bkDirectories[i]);
for(File file: dir.listFiles()){
try{
if(file.isFile()){
FileUtils.copyFileToDirectory(file, dest);
publish(file.getAbsolutePath() + "\n");
} else if (file.isDirectory()){
FileUtils.copyDirectoryToDirectory(file, dest);
publish(file.getAbsolutePath() + "\n");
}
if(getDirSize(file) >= ONE_PERCENT){
currentPercent = getDirSize(file)/ONE_PERCENT;
progressBar.setValue((int)currentPercent);
currentSize = 0;
} else {
currentSize = currentSize + getDirSize(file);
if(currentSize >= ONE_PERCENT){
currentPercent = currentSize/ONE_PERCENT;
currentPercent++;
progressBar.setValue((int)currentPercent);
currentSize = 0;
}
}
} catch (IOException e){
e.printStackTrace();
}
}
}
return null;
}
@Override
public void process(List<String> chunks){
for(String path : chunks){
txtCopiedDirs.append(path);
}
}
@Override
public void done(){
closeWindow();
}
}
public static Long getDirSize(File file) {
long size = 0L;
if (file.isFile() && file != null){
size += file.isDirectory() ? getDirSize(file) : file.length();
} else if (file.isDirectory()){
for (File f : file.listFiles()) {
size += f.isDirectory() ? getDirSize(f) : file.length();
}
}
return size;
}
/* Close current window */
public void closeWindow() {
WindowEvent close = new WindowEvent(this, WindowEvent.WINDOW_CLOSING);
Toolkit.getDefaultToolkit().getSystemEventQueue().postEvent(close);
System.exit(0);
}
}
编辑 #2:
我对 createGUI() 方法进行了一些更改,以避免 contentPane 的布局为空:
public void createGUI(){
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("Backup Progress");
setBounds(100, 100, 450, 300);
contentPane = new JPanel(new BorderLayout());
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
txtCopiedDirs = new JTextArea(10, 50);
txtCopiedDirs.setEditable(false);
scrollPane = new JScrollPane(txtCopiedDirs);
contentPane.add(scrollPane, BorderLayout.CENTER);
btnCancel = new JButton("Cancel");
btnCancel.setBounds(169, 227, 89, 23);
btnCancel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
closeWindow();
}
});
contentPane.add(btnCancel);
progressBar = new JProgressBar(0, 100);
progressBar.setBounds(10, 192, 414, 24);
progressBar.setValue(0);
contentPane.add(progressBar);
lblCopying = new JLabel("Now backing up your files....");
lblCopying.setBounds(10, 11, 157, 34);
contentPane.add(lblCopying);
setVisible(true);
task = new Task();
task.execute();
}
【问题讨论】:
-
让你的
SwingWorker<Void,String>调用publish(filesNameString)并覆盖process,在处理过程中追加到txtDirs
标签: java implementation jtextarea swingworker jscrollbar