我正在制作一个旨在备份的程序。我SwingWorker
进行备份并将其正在执行的内容发布到JTextArea
。我想要一个按钮来取消工人,(有一个未知的数量一次初始化)所以这就是我调用摇摆工人和取消方法的原因:
package main;
import java.io.File;
import java.util.ArrayList;
import javax.swing.SwingWorker;
public class test2 {
SwingWorker bw;
static ArrayList bgWorker = new ArrayList();
ArrayList al = new ArrayList(); // this is the list of files selected
static boolean bwInitiallized = false;
public void startBackup() throws Exception {
Panel.txtArea.append("Starting Backup...\n");
for (int i = 0; i < al.size(); i++) {
/**
* THIS IS WHERE I NEED TO CREATE THE FOLDER THAT EACH BACKUP FILE
* WILL GO INTO EX: SC2 GOES INTO A FOLDER CALLED SC2 AND RIOT GOES
* TO RIOT, ALL WITHIN THE DIRECTORY CHOSEN
*/
File file = new File((String) al.get(i));
File directory = new File(dir); // dir is gotten by a JFileChooser.
bw = new BackgroundWorker(Panel.txtArea, file, directory);
bgWorker.add(bw);
bwInitiallized = true;
bw.execute();
/**
* follows to the bottom of the txtarea
*/
int x;
Panel.txtArea.selectAll();
x = Panel.txtArea.getSelectionEnd();
Panel.txtArea.select(1, x);
}
}
public static void cancel() {
BackgroundWorker bg;
if (bwInitiallized) {
bwInitiallized = false;
Panel.txtArea.append("Cancelling...\n");
for (int i = 0; i < bgWorker.size(); i++) {
bg = (BackgroundWorker) bgWorker.get(i);
bg.cancel(true);
}
Panel.txtArea.append("Canceled backUp!\n");
} else {
Panel.txtArea.append("Cannot Cancel! Not Initiallized!\n");
}
}
}
好吧,由于我无法弄清楚的原因,这并没有取消任何一个(据我所知)。我唯一能想到的就是当我做的时候。
bg = (BackgroundWorker) bgWorker.get(i);
bg.cancel(true);
它不是我认为它做的,但是idk。我究竟做错了什么?提前谢谢!