2017-01-09 30 views
0

我正在執行壓縮和刪除文件的應用程序。到目前爲止,我設法實現了SwingWorker,但它不顯示和更新TextArea。結果僅在控制檯中顯示。有人能用一個例子告訴我我做錯了什麼,或者我錯過了什麼?我所做的代碼如下所示:更新JTextArea以顯示進度

import java.awt.*; 
import java.awt.event.*; 
import java.io.*; 
import java.util.zip.*; 
import javax.swing.*; 
import java.util.List; 

@SuppressWarnings("serial") 
public class zipfiles2 extends JFrame { 
static final int DEFAULT_BUFFER_SIZE = 1024 * 4; 
private File datei, parent; 
private String name; 

class Task extends SwingWorker<String, String> 
{ 
    String status; 
    JTextArea statusprocess; 

    public Task(JTextArea statusprocess) 
    { 
     this.statusprocess = statusprocess; 
    } 
    private String addToZip(String path, String srcFile, ZipOutputStream zipOut) throws IOException 
    {   
    File file = new File(srcFile); 
    String filePath = "".equals(path) ? file.getName() : path + "/" + file.getName(); 
    if (file.isDirectory()) 
    { 
     for (String fileName : file.list()) 
     { 
     status = "Folder: "+srcFile + "/" +" is being added to the zip file"; 
     addToZip(filePath, srcFile + "/" + fileName, zipOut); 
     } 
    } 
    else 
    { 
     if (new File(filePath).canRead()) 
     { 
      status = "File "+filePath+"is being zipped"; 
     } 
     else 
     { 
      status = "File: "+filePath+" is being zipped"; 
      zipOut.putNextEntry(new ZipEntry(filePath)); 

      FileInputStream in = null; 
      try { 
        in = new FileInputStream(srcFile); 
      } catch (FileNotFoundException e) { 
       new File(srcFile).delete(); 
      } 

      byte[] buffer = new byte[DEFAULT_BUFFER_SIZE]; 
      int len; 
      while ((len = in.read(buffer)) != -1) { 
       zipOut.write(buffer, 0, len); 
      } 
      in.close(); 
     } 
    } 
    return status; 
    } 

public String zipFile(String fileToZip, String zipFile, boolean excludeContainingFolder) throws IOException 
    {   
     ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(zipFile));  
     File srcFile = new File(fileToZip); 

     if(excludeContainingFolder && srcFile.isDirectory()) 
     { 
      for(String fileName : srcFile.list()) 
      { 
       addToZip("", fileToZip + "/" + fileName, zipOut); 
      } 
     } 
     else 
     { 
      addToZip("", fileToZip, zipOut); 
     } 
     zipOut.flush(); 
     zipOut.close(); 
     status = "The zip file " + zipFile + " was created successfully"; 
     return status; 
    } 
    public String deleteDirectory(File f) throws IOException { 
     if (f.isDirectory()) { 
      for (File c: f.listFiles()) { 
       status= "File: "+c.getName()+" is being deleted"; 
       deleteDirectory(c); 
      } 
      f.delete(); 
     } 
     else 
     { 
      f.delete(); 
     } 
     return status; 

    } 
@Override 
protected String doInBackground() throws Exception { 
    zipFile(datei.getAbsolutePath(), parent.getAbsolutePath()+"/"+name, true); 
    publish(status); 
    deleteDirectory(datei); 
    publish(status); 
    return status; 
} 

@Override 
protected void process(List<String> chunks) 
{ 
    for (String status : chunks) { 
     statusprocess.append(status); 
    } 
} 
} 
public zipfiles2() { 

    JFileChooser browser = new JFileChooser(); 
    browser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES); 
    JPanel panel = new JPanel(); 
    final JTextArea showprogress = new JTextArea(); 

    ActionListener fileValidation = new ActionListener() 
    { 
    public void actionPerformed(ActionEvent actionEvent) 
    { 
     JFileChooser browser2 = (JFileChooser) actionEvent.getSource(); 
     String command = actionEvent.getActionCommand(); 

     if (command.equals(JFileChooser.APPROVE_SELECTION)) 
     { 
      datei = browser2.getSelectedFile(); 
      parent = browser2.getCurrentDirectory(); 
      File[] dio = parent.listFiles(); 

      if (datei.isFile()) { name = datei.getName().substring(0, datei.getName().lastIndexOf("."))+".zip"; } 
      else { name = datei.getName()+".zip"; } 

      for (File dateien: dio) 
      { 
       if (dateien.isFile() && dateien.getName().endsWith(".zip")) 
       { 
        if (name.equals(dateien.getName())) 
        { 
         JOptionPane.showMessageDialog(null,"Eine Zip-Datei mit der Name der ausgewählten Datei existiert bereits im Ordner", "Validierung", JOptionPane.WARNING_MESSAGE); 
         new zipfiles2().setVisible(true); 
        } 
       } 
      } 
      Task task = new Task(showprogress); 
      task.execute(); 
     } 
     else 
     { 
      System.exit(0); 
     } 
     } 

    }; 

    browser.addActionListener(fileValidation); 


    JProgressBar progessbar = new JProgressBar(); 
    progressbar.setIndeterminate(true); 
    panel.add(progressbar); 
    panel.add(showprogress); 

    Dimension ScS = Toolkit.getDefaultToolkit().getScreenSize(); 
    this.setTitle("Zip Tool"); 
    this.setSize(200, 90); 
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    this.setLocation(ScS.width/2 - this.getSize().width/2, ScS.height/2 - this.getSize().height/2); 

    browser.showOpenDialog(this); 
    this.add(panel, BorderLayout.PAGE_START); 
} 
public static void main(String[] args) { 
    java.awt.EventQueue.invokeLater(new Runnable() { 
      public void run() { 
       try 
       { 
        UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");  
       } 
       catch (Exception ex) 
       { 
        ex.printStackTrace(); 
       } 
       new zipfiles2().setVisible(true); 
      } 
     }); 
    } 
} 

編輯:上面的代碼是一個新的版本,與修正建議。但是,它並沒有顯示我的GUI。我還錯過了什麼嗎?

第二次編輯:我的GUI顯示,但我的textarea沒有被更新。我應該如何將其他方法的狀態傳遞給doInBackground方法才能發佈?也許一個ArrayList類型的字符串?

+0

難道不會在狀態更新了'publish'方法?我想你忘了那部分。 – cubrr

回答

1

你沒有正確重寫process方法,簽名是這樣的:

protected void process(List<V> chunks) 
你的情況

這將是:

protected void process(List<String> chunks) 

使用@Override註釋就可以防止這個問題。

然後,你會用這樣的說法:

 @Override 
    protected void process(List<String> chunks) { 
     for (String status : chunks) { 
      statusprocess.append(status); 
     } 
    } 
+0

那麼,這是否意味着我將變量狀態保存在整數列表中? –

+0

@AnaZerpa:我的錯,我剛剛修正了答案,因爲使用了泛型,在你的情況下,塊將是'String'類型。 'publish'將負責使用您提供的參數創建一個列表。 – Berger

+0

喜歡這個? @覆蓋 \t保護無效過程(列表組塊) \t { \t \t statusprocess.append(狀態); \t} –