2011-06-21 100 views
2

我是Java新手。 我想寫一個程序,使文件 arcive,我想使用進度條來顯示壓縮進度 有我的代碼,但它不工作 只顯示100%,工作完成後。Java文件進度條

 getContentPane().add(progressBar); 
    progressBar.setBorder(new CompoundBorder(null, null)); 
    springLayout.putConstraint(SpringLayout.EAST, progressBar, 0, SpringLayout.EAST, messageLabel); 
    springLayout.putConstraint(SpringLayout.WEST, progressBar, 0, SpringLayout.WEST, messageLabel); 
    springLayout.putConstraint(SpringLayout.SOUTH, progressBar, 165, SpringLayout.NORTH, getContentPane()); 
    springLayout.putConstraint(SpringLayout.NORTH, progressBar, 5, SpringLayout.SOUTH, uploadLocalButton); 
    progressBar.setValue(0); 
    progressBar.setMaximum(100); 
    progressBar.setMinimum(0); 
    progressBar.setStringPainted(true); 
... 
public void doZip(String filename,String outFilename) 
{ 
    try { 
     byte[] dataBytes = new byte[1024]; 
     File file = new File(outFilename); 
     file.createNewFile(); 
     FileOutputStream fos = new FileOutputStream(file); 
     ZipOutputStream zos = new ZipOutputStream(fos); 
     File fil = new File(filename); //"Users/you/image.jpg" 
     long length= fil.length(); 
     System.out.println(length); 
     zos.putNextEntry(new ZipEntry(fil.getName()));//image.jpg 
     FileInputStream in = new FileInputStream(filename); 
     int current=0; 
     int len; 

     while ((len = in.read(dataBytes)) > 0) 
     { current += len; 
     messageLabel.setText(Integer.toString(current)); 
     System.out.println(current); 
     final double progres=(((double)current/(double)length)*100); 
     progressBar.setValue((int)progres);    
      zos.write(dataBytes, 0, dataBytes.length); 
     } 

     zos.closeEntry(); 
     zos.close(); 
     in.close(); 
}catch (IOException e) { 
     JOptionPane.showMessageDialog(null, 
       "Access denied. File or patch not exist or in currently in use.","Error", 
       JOptionPane.ERROR_MESSAGE); 
     e.printStackTrace(); 

    }} 

也許有人知道問題在哪裏?


我打電話doZip按鈕。 我想這

while ((len = in.read(dataBytes)) > 0) 
     { current += len; 
     zos.write(dataBytes, 0, dataBytes.length); 
     final double progres=(((double)current/(double)length)*100); 
     try{ 
      SwingUtilities.invokeLater(new Runnable(){ 
       public void run(){ 
       progressBar.setValue((int)progres); 
       } 
      }); 
      java.lang.Thread.sleep(100); 
     }catch(InterruptedException e){;} 

但它也doesent工作,不僅使拉鍊opperation的過程更加長。

+0

嘗試將您的調用包裝爲線程中的'doZip' – dcn

回答

2

我假設你從AWT線程的某個地方調用doZip(例如,直接由動作處理程序(作爲對點擊響應的響應)調用)。因此,直到動作(壓縮)完成後UI纔會更新,即使您在兩者之間設置相應的進度。

一種解決方案是在單獨的線程中啓動doZip(通常,建議避免使用任何昂貴的AWT線程操作,但只做基本的「動作處理」,並從那裏觸發長時間運行操作...)