2012-08-28 46 views
2

我正在製作一個旨在作爲備份的程序。我有SwingWorker做備份併發布它正在做什麼JTextArea。我希望有一個按鈕取消工人,(有一次initiallized他們的未知量),所以這是我對揮杆工人的電話,和取消方法:取消SwingWorker的問題

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

請改善您的Java標識符的命名,使其符合標準。我們很難去理解別人的代碼,他們不需要爲我們更難。另請考慮創建併發布[sscce](http://sscce.org)。您在此的努力將不勝感激。 –

+0

我對你的命名可能是錯的;它可能是好的。面板是靜態字段的類嗎?如果是這樣,yuck。 –

+0

即時通訊不知道你的意思...記住,我仍然有點小菜 – PulsePanda

回答

4

我會爲每個文件創建一個class FileWorker extends SwingWorker<File, File>的實例,併爲其管理class Supervisor extends SwingWorker<Queue<File>, File>的單個實例,如example中所建議的。您可以允許用戶取消個人FileWorker或讓Supervisor全部取消。使用cancel()的示例顯示爲here

在任何情況下,請使用相應的SwingWorker類型參數以確保安全,並按照@Hovercraft的建議批判性地檢查您的設計。

+0

1+希望我能再次投票你的鏈接到答案/代碼! –