取消SwingWorker时出现问题

时间:2012-08-28 02:37:25

标签: java swing backup swingworker

我正在制作一个旨在备份的程序。我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。我究竟做错了什么?提前谢谢!

1 个答案:

答案 0 :(得分:4)

我会为每个文件创建一个class FileWorker extends SwingWorker<File, File>的实例,并根据example的建议为class Supervisor extends SwingWorker<Queue<File>, File>创建一个FileWorker实例。您可以允许用户取消个人Supervisor或让cancel()取消所有人。使用SwingWorker的示例显示为here

在任何情况下,请使用适当的{{1}}类型参数以确保安全,并按@Hovercraft评论中的建议严格检查您的设计。