2013-10-30 69 views
0

什麼,我試圖做的是,當我點擊一個按鈕,我的一些文件從如USB便攜式驅動器複製這些文件複製到本地驅動器上,然後我讀,我複製ealier所有CSV文件,我把它的價值觀一個arraylist並將其注入到數據庫中,然後我可以刪除這些文件,並且我想根據進程完成情況在進度條中顯示進程。所以這是我做的:爲什麼JProgressBar值不刷新?

  void main() 
      { 
      JButton btnTransfer = new JButton("Transfer"); 
         Image transferIMG = ImageIO.read(new File("C:\\Users\\User\\Desktop\\images\\transfer.png")); 
         btnTransfer.setIcon(new ImageIcon(transferIMG)); 
         btnTransfer.setPreferredSize(new Dimension(110, 90)); 
         btnTransfer.setOpaque(false); 
         btnTransfer.setContentAreaFilled(false); 
         btnTransfer.setBorderPainted(false); 
         btnTransfer.setVerticalTextPosition(SwingConstants.BOTTOM); 
         btnTransfer.setHorizontalTextPosition(SwingConstants.CENTER); 
         btnTransfer.addActionListener(new ActionListener() 
         { 
           public void actionPerformed(ActionEvent e) 
           { 
            File csvpath = new File(fileList1.getSelectedValue() + "\\salestablet\\report\\csv"); 
            File htmlpath = new File(fileList1.getSelectedValue() + "\\salestablet\\report\\html"); 
            String removepath = fileList1.getSelectedValue() + "\\salestablet\\report"; 

            if(csvpath.listFiles().length > 0 && htmlpath.listFiles().length > 0) 
            { 
             File[] csvarr = csvpath.listFiles(); 
             File[] htmlarr = htmlpath.listFiles(); 

             try 
             { 
              copyFileUsingStream(csvarr, htmlarr, txt.getText(), removepath); 
             } 
             catch (IOException e1) 
             { 
              // TODO Auto-generated catch block 
              e1.printStackTrace(); 
             } 
           } 
           } 
         }); 

     JPanel ButtonCont = new JPanel(new GridLayout(4, 1, 5, 0)); 
        ButtonCont.setBackground(Color.LIGHT_GRAY); 

        ButtonCont.add(btnTransfer); 

     gui.add(ButtonCont , BorderLayout.EAST); 

        frame.setContentPane(gui); 
        frame.setExtendedState(Frame.MAXIMIZED_BOTH); 
        frame.setMinimumSize(new Dimension(900, 100)); 
        frame.pack(); 
        frame.setLocationByPlatform(true); 
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
        frame.setVisible(true);   
      } 

     private static void copyFileUsingStream(File[] csvsources, File[] htmlsources, String dest, String removepath) throws IOException 
      { 
       int count = 0; 
       int MaxCount = countprocess(csvsources, htmlsources); 

       progressBar = new JProgressBar(0, MaxCount); 
       progressBar.setStringPainted(true); 

       InputStream is = null; 
       OutputStream os = null; 

       String csvfolderpath = dest + "\\csv"; 
       String htmlfolderpath = dest + "\\html"; 

       if(!(new File(csvfolderpath)).exists()) 
       { 
        (new File(csvfolderpath)).mkdirs(); //create csv folder; 
       } 

       if(!(new File(htmlfolderpath)).exists()) 
       { 
        (new File(htmlfolderpath)).mkdirs(); //create csv folder; 
       } 

       for(int i= 0; i < csvsources.length; i++) //copy all csv files to csv folder 
       { 
        try 
        { 
         is = new FileInputStream(csvsources[i]); 
         os = new FileOutputStream(csvfolderpath + "\\" + csvsources[i].getName()); 
         byte[] buffer = new byte[1024]; 
         int length; 

         while ((length = is.read(buffer)) > 0) 
         { 
          os.write(buffer, 0, length); 
         } 
        } 
        finally 
        { 
         count += 1; 
         progressBar.setValue((count/MaxCount) * 100); 
         //progressBar.repaint(); 
         //progressBar.revalidate(); 
         progressBar.update(progressBar.getGraphics()); 

         is.close(); 
         os.close(); 
        } 
       } 

       for(int i= 0; i < htmlsources.length; i++) //copy all html, images and css to html folder 
       { 
        if(htmlsources[i].isFile()) 
        { 
         try 
         { 
          is = new FileInputStream(htmlsources[i]); 
          os = new FileOutputStream(htmlfolderpath + "\\" + htmlsources[i].getName()); 
          byte[] buffer = new byte[1024]; 
          int length; 

          while ((length = is.read(buffer)) > 0) 
          { 
           os.write(buffer, 0, length); 
          } 
         } 
         finally 
         { 
          count += 1; 
          progressBar.setValue((count/MaxCount) * 100); 
          //progressBar.repaint(); 
          //progressBar.revalidate(); 
          progressBar.update(progressBar.getGraphics()); 

          is.close(); 
          os.close(); 
         } 
        } 
        else if(htmlsources[i].isDirectory()) //for subfolder 
        { 
         String path = dest + "\\html\\" + htmlsources[i].getName(); 

         if(!new File(path).exists()) 
         { 
          (new File(path)).mkdirs(); //create subfolder; 
         } 

         File[] arr = (new File(htmlsources[i].getAbsolutePath())).listFiles();  

         for(int j = 0; j < arr.length; j++) 
         { 
          if(arr[j].isFile()) 
          { 
           try 
           { 
            is = new FileInputStream(arr[j]); 
            os = new FileOutputStream(path + "\\" + arr[j].getName()); 
            byte[] buffer = new byte[1000000]; 
            int length; 

            while ((length = is.read(buffer)) > 0) 
            { 
             os.write(buffer, 0, length); 
            } 
           } 
           finally 
           { 
            if(htmlsources[i].getName().contains("images")) 
            { 
             count += 1; 
             progressBar.setValue((count/MaxCount) * 100); 
             //progressBar.repaint(); 
             //progressBar.revalidate(); 
             progressBar.update(progressBar.getGraphics()); 
            } 

            is.close(); 
            os.close(); 
           } 
          } 
         } 
        } 
       } 

       ArrayList<String > DBValues = new ArrayList<String>(); //read all csv files values 

       File f1 = new File(csvfolderpath); 
       for(int i = 0; i < f1.listFiles().length; i++) 
       { 
        if(f1.listFiles()[i].isFile()) 
        { 
         FileReader fl = new FileReader(f1.listFiles()[i]); 
         BufferedReader bfr = new BufferedReader(fl);  

         for(int j = 0; j < 2; j++) 
         { 
          if(j == 1) 
          { 
           DBValues.add(bfr.readLine()); 

           count += 1; 
           progressBar.setValue((count/MaxCount) * 100); 
           //progressBar.repaint();  
           //progressBar.revalidate(); 
           progressBar.update(progressBar.getGraphics()); 
          } 
          else 
          { 
           bfr.readLine(); 
          } 
         } 
         bfr.close(); 
        } 
       } 

       /*for(int x = 0; x < DBValues.size(); x++) 
       { 
        //System.out.println(DBValues.get(x)); 
       }*/ 

       //removing csv in local computer 
       File f2 = new File(csvfolderpath); 
       File[] removelist = f2.listFiles(); 
       for(int x = 0; x < removelist.length; x++) 
       { 
        if(removelist[x].isFile()) 
        { 
         removelist[x].delete(); 

         count += 1; 
         progressBar.setValue((count/MaxCount) * 100); 
         // progressBar.repaint();  
         //progressBar.revalidate(); 
          progressBar.update(progressBar.getGraphics()); 
        } 
       } 

       //removing csv in device 
       File f3 = new File(removepath + "\\csv"); 
       if(f3.isDirectory()) 
       { 
        removelist = f3.listFiles(); 

        for(int y = 0; y < removelist.length; y++) 
        { 
         try 
         { 
          if(removelist[y].isFile()) 
          { 
           //System.out.println(removelist[y].getName()); 
           removelist[y].delete(); 
           count += 1; 
           progressBar.setValue((count/MaxCount) * 100); 
           //progressBar.repaint(); 
          // progressBar.revalidate(); 
          progressBar.update(progressBar.getGraphics()); 
          } 
         } 
         catch(Exception e) 
         { 
          System.out.println(e); 
         } 
        } 
       } 

       //removing html and images in device 
       File f4 = new File(removepath + "\\html"); 
       if(f4.isDirectory()) 
       { 
        removelist = f4.listFiles(); 

        for(int z = 0; z < removelist.length; z++) 
        { 
         try 
         { 
          if(removelist[z].isFile()) 
          { 
           removelist[z].delete(); 

           count += 1; 
           progressBar.setValue((count/MaxCount) * 100); 
          // progressBar.repaint(); 
          // progressBar.revalidate(); 
          progressBar.update(progressBar.getGraphics()); 
          } 
          else if(removelist[z].isDirectory()) 
          { 
           if(removelist[z].getName().contains("images")) 
           { 
            File[] subfolder = removelist[z].listFiles(); 

            for (int idx = 0; idx < subfolder.length; idx++) 
            { 
             if(subfolder[idx].isFile()) 
             { 
              subfolder[idx].delete(); 

              count += 1; 
              progressBar.setValue((count/MaxCount) * 100); 
             // progressBar.repaint(); 
             // progressBar.revalidate(); 
             progressBar.update(progressBar.getGraphics()); 
             } 
            } 
           } 
          } 
         } 
         catch(Exception e) 
         { 
          System.out.println(e); 
         } 
        } 
       } 

       /* JProgressBar progressBar = new JProgressBar(); 
        progressBar.setValue(25); 
        progressBar.setStringPainted(true);*/ 
        Border border = BorderFactory.createTitledBorder("Reading..."); 
        progressBar.setBorder(border); 


       gui.add(progressBar, BorderLayout.SOUTH); 
       gui.repaint(); 
       gui.revalidate(); 


       // System.out.println(count); 
      } 

    private static int countprocess(File[] csv, File[] html_image) 
    { 
     int x = 0; 
     int y = 0; 
     int z = 0; 

     for(int i = 0; i < csv.length; i++) 
     { 
      if(csv[i].isFile()) 
      { 
       x += 1; 
      } 
     } //get total count of csv files throught loop 

     for(int i = 0; i < html_image.length; i++) 
     { 
      if(html_image[i].isFile()) 
      { 
       y += 1; 
      } 
      else if(html_image[i].isDirectory()) 
      { 
       if(html_image[i].getName().contains("images")) 
       { 
        File[] flist = html_image[i].listFiles(); 

        for(int j = 0; j < flist.length; j++) 
        { 
         z += 1; 
        } 
       } 
      } //get total count of html and images files throught loop 
     } 

     return ((4*x) + (2*y) + (2*z)); 
    } 

,所以我試圖通過設置刷新我的進度條值是這樣的

progressBar.setValue((count/MaxCount) * 100);

值,但不知何故,我不能讓它工作,我進度條並沒有顯示它的進展情況,如1%2%3%.. 10%等等。相反,它僅在完成流程時顯示100%。我在這裏錯過了什麼? 注:我也試圖設置我的進度欄值這種方式progressBar.setValue(count);仍然沒有運氣。

+0

請今後解決壓痕:-) – raffian

回答

0

你在你的進度條的值設置爲完成百分比。但是進度條的最大值實際上是項目的總數。

相反,你需要只是你的進度值設置爲當前計,擺脫計算爲%的。

喜歡的東西:

progressBar.setValue(count); 

而且你應該做的的SwingWorker線程的長期運行的任務,這樣你就不必強制GUI的重繪。

+0

感謝名單,我當前的代碼之前,我曾嘗試使用progressBar.setValue(count)ealier,但它沒有工作,所以我想我應該計算它手動。順便說一句關於「SwingWorker」你能告訴我怎麼做嗎?我對此並不是很熟悉,thanx之前。 – NomNomNom

+0

你甚至不必爲SwingWorker瘋狂。通過將進度更新包裝到Runnable中,確保進度條的更新發生在swing渲染線程上,然後將其更改爲[SwingUtilities.invokeLater](http://docs.oracle.com/javase/6/docs /api/javax/swing/SwingUtilities.html#invokeLater(java.lang.Runnable)) – David

+0

@David,問題是加載發生在EDT上。它需要被分解成一個SwingWorker,他可以根據你的建議調用invokeLater。 – jzd

1

查看你的整個代碼將需要一段時間。但是,在btnTransfer.addActionListeneractionPerformed函數中,您試圖複製可能需要一段時間的流。在事件派發線程中執行任何類型的事件偵聽器。請致電refer to this answer瞭解更多詳情。

現在,作爲一個快速的解決方案:

  • 把你copyFileUsingStream(csvarr, htmlarr, txt.getText(), removepath);功能的在線線程內:

    new Thread() 
        { 
        public void run() 
        { 
         copyFileUsingStream(csvarr, htmlarr, txt.getText(), removepath); 
        } 
    }.start(); 
    
    } 
    
  • JProgressBar你的進度更新內部SwingUtilities.invokeLater,並通過使(count/MaxCount)計算鑄造double其中之一,如下:

    SwingUtilities.invokeLater(new Runnable() { 
    
        @Override 
        public void run() { 
    
        count += 1; 
        progressBar.setValue((int) (((double)count/ MaxCount) * 100)); 
        } 
    }); 
    

count是本地copyFileUsingStream功能,請儘量聲明它在你的類上下文來訪問和改變。

SwingWorker優選的是,這樣的任務。

教程資源:

  1. Worker Threads and SwingWorker
  2. How to use progress bars with swing worker
  3. ProgressBar Demo with SwingWorker
+0

thx,會試試看,我會讓你知道它是否工作。 – NomNomNom

+0

@HendraLim,請注意'count/MaxCount'的進度計算,因爲我在帖子 – Sage

+0

中表示過我已經嘗試了您的建議,但仍然沒有運氣。無論如何它現在工作,我正在使用雙線程,使其工作。無論如何,我正在投票你的好建議,thx。 – NomNomNom