Reputation: 1856
Im making a program that is designed to be a backup. i have SwingWorker
doing the backup and posting what it's doing to a JTextArea
. I want a button to cancel the worker, (there are a unknown amount of them initiallized at one time) so this is what i have for the calling of the swing workers, and the cancel method:
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");
}
}
}
Well, for reasons that i cannot figure out, this does not cancel any of them (as far as i'm aware). the only thing that i can think of is when i do
bg = (BackgroundWorker) bgWorker.get(i);
bg.cancel(true);
it doesnt do what i think it does, but idk. what am i doing wrong? thanks in advance!
Upvotes: 2
Views: 238
Reputation: 205785
I'd create an instance of class FileWorker extends SwingWorker<File, File>
for each file and a single instance of class Supervisor extends SwingWorker<Queue<File>, File>
to manage them, as suggested in this example. You could allow the user to cancel an individual FileWorker
or let the Supervisor
cancel them all. An example using cancel()
is shown here.
In any case, use the appropriate SwingWorker
type parameters for safety and critically examine your design as suggested in comments by @Hovercraft.
Upvotes: 4