2015-05-10 33 views
2

如下面的代碼所示,我有4個功能,我手動設置進度監視器的每個進度間隔= 25%。進度監視器:進度間隔

但是如果我有20或更多的函數,我的方法將更不切實際的手動設置進度間隔。

如果給定X個函數,設置進度間隔會是更好的方法嗎?

class Task extends SwingWorker<Void, Void> { 
    @Override 
    public Void doInBackground() { 
     int progress = 0; 
     setProgress(0); 
     while (progress < 100 && !isCancelled()) 
     { 
      functionA(); 
      try { 
       Thread.sleep(1000); 
      }catch(InterruptedException ex) { 
       ex.printStackTrace(); 
      } 
      progress += 25; 
      setProgress(Math.min(progress, 100)); 

      taskOutput.setText("Step 2"); 
      functionB(); 
      progress += 25; 
      setProgress(Math.min(progress, 100)); 

      try { 
       Thread.sleep(1000); 
      }catch(InterruptedException ex) { 
       ex.printStackTrace(); 
      } 

      taskOutput.setText("Step 3"); 
      functionC(); 
      progress += 25; 
      setProgress(Math.min(progress, 100)); 

      try { 
       Thread.sleep(1000); 
      }catch(InterruptedException ex) { 
       ex.printStackTrace(); 
      } 

      taskOutput.setText("Step 4"); 
      functionD(); 
      try { 
       Thread.sleep(1000); 
      }catch(InterruptedException ex) { 
       ex.printStackTrace(); 
      } 
      progress += 25; 
      setProgress(Math.min(progress, 100)); 
     } 
     return null; 
    } 

回答

2
int numberOfFunctions = 20; 
int progress = 0; 
... 
function1(); 
setProgress((++progress * 100)/numberOfFunctions); // progress is 5% 
... 
function20(); 
setProgress((++progress * 100)/numberOfFunctions); // progress is 100%