为什么SwingWorkers不按预期更新textArea?

时间:2012-05-07 10:58:26

标签: java swing user-interface swingworker

我使用swingworkers来提取zipfile,并将提取的prosecc附加到GUI中的textArea。它只从压缩文件中提取一个项目,并且没有在textArea中显示任何内容。

任何人都可以建议任何解决方案吗?

public class UnzipWorkers extends SwingWorker<String,Void> {
private WebTextArea statusTextArea;
private File archive,outputDir;

public UnzipWorkers(WebTextArea statusTextArea,File archive,File outputDir) {
    this.archive=archive;
    this.outputDir=outputDir;
    this.statusTextArea = statusTextArea;
}

@Override
protected String doInBackground() throws Exception {
        statusTextArea.append(String.valueOf(System.currentTimeMillis()));
        try {
            ZipFile zipfile = new ZipFile(archive);
            for (Enumeration e = zipfile.entries(); e.hasMoreElements(); ) {
                ZipEntry entry = (ZipEntry) e.nextElement();
                unzipEntry(zipfile, entry, outputDir);

            }
        } catch (Exception e) {
            OeExceptionDialog.show(e);
        }

    return "Extracted successfully: " + archive.getName() + "\n";  
}

@Override
protected void done() {
    super.done();
    try {
        statusTextArea.append( get());
        FileTreePanel.btnRefresh.doClick();
    } catch (InterruptedException e) {
        e.printStackTrace();  
    } catch (ExecutionException e) {
        e.printStackTrace(); 
    }
}

private String unzipEntry(ZipFile zipfile, final ZipEntry entry, File outputDir)  {
    String success = "Extracted failed: "+ entry + "\n";
    if (entry.isDirectory()) {
        createDir(new File(outputDir, entry.getName()));
    }

    File outputFile = new File(outputDir, entry.getName());
    if (!outputFile.getParentFile().exists()){
        createDir(outputFile.getParentFile());
    }
    try {
        BufferedInputStream inputStream = new BufferedInputStream(zipfile.getInputStream(entry));
        BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(outputFile));
        IOUtils.copy(inputStream, outputStream);
        outputStream.close();
        inputStream.close();
        success="Extracted successfully: " + entry + "\n";
    }catch (IOException io){
        OeExceptionDialog.show(io);
    }catch (NullPointerException n){
        OeExceptionDialog.show(n);
    }catch (ArithmeticException a){
        OeExceptionDialog.show(a);
    }
    return success;
}

private void createDir(File dir) {
    if (!dir.exists()) {
        try {
            dir.mkdirs();
        } catch (RuntimeException re) {
            OeExceptionDialog.show(re);
        }
    }
}
}

1 个答案:

答案 0 :(得分:5)

SwingWorker未指定以这种方式工作,对于来自doInBackground()的定期输出,有方法process()publish(),您可以

1)使用Runnable#Thread代替SwingWorker,然后您通过添加JTextArea.append()进行编码,并将其包含在invokeLater()

2)将process()publish()添加到SwingWorker,在此方法中添加IOStream并定期附加到JTextArea

3)我建议to use method get() for implemented reason