2014-03-06 187 views
0

我有一個需要被GUI調用的大程序。在用戶按下開始按鈕之後,GUI具有需要更新的進度條(例如5%... 10%)。 問題是執行的後臺任務沒有固定的執行時間。因此,在某種程度上可以測量在doInBackground()方法中執行的任務的進度(我正在嘗試使用SwingWorker)。或者我應該去一個不確定的進度條。 我無法清楚地理解Oracle教程頁面上提供的示例,但無法找到解釋如何使用進度欄的體面的頁面。 任何幫助將不勝感激。更新進度條

+0

http://stackoverflow.com/questions/277007/how-to-use -jprogressbar與你的問題非常相似。 – MemLeak

+0

請發佈您的代碼 – Benjamin

+0

@MemLeak我的程序的輸入沒有固定的大小,因此執行時間會有所不同。該程序使用遺傳算法,並使用線程實現。 – Sashank

回答

1

根據問題,我會用一個無限進度條

public class Indeterminate extends JProgressBar { 

    private static final long serialVersionUID = -281761375041347893L; 

    /*** 
    * initial the ProgressBar 
    */ 
    public IndeterminateProgressBar() { 
     super(); 
     setIndeterminate(true); 
     EventQueue.invokeLater(new Runnable() { 

      @Override 
      public void run() { 
       setVisible(false); 
      } 
     }); 
    } 

    /** 
    * call this, if you start a long action 
    */ 
    public void start() { 
     EventQueue.invokeLater(new Runnable() { 

      @Override 
      public void run() { 
       setVisible(true); 
      } 
     }); 
    } 

    /** 
    * if you have finished, call this 
    */ 
    public void end() { 
     EventQueue.invokeLater(new Runnable() { 

      @Override 
      public void run() { 
       setVisible(false); 
      } 
     }); 
    } 

} 

像這樣來使用:

ActionListener startButtonListener = new ActionListener() { 

    @Override 
    public void actionPerformed(ActionEvent e) { 

     new Thread(new Runnable() { 

      @Override 
      public void run() { 

       try { 
        progressBar.start(); 
        // long operation 

       } catch (Exception e) { 
        // handle excpetion 
       } finally { 
        progressBar.end(); 

       } 

      } 
     }).start(); 

    } 
}; 
+0

中使用「public void propertyChange(PropertyChangeEvent evt)」方法。謝謝你回覆我會試試這個。 – Sashank