2

這是我第一次必須使用進度條工作,並且我面臨一個問題,除了我試圖從它始終保持0%的地方呼叫它的setValue(x)以及在我的方法程序完成後直接進入100%。JProgressBar不會在一個循環內實時更新

我試圖做一個擴展線程的內部類,然後我試圖在我的「主要」方法內啓動一個新的線程,然後在最後我嘗試使用觀察者。這些似乎那些根據這一職位,但遺憾的是沒有給我

Update JProgressBar from new Thread

Problem making a JProgressBar update values in Loop (Threaded)

請,能有人幫我工作過???

public class MainClass {  

private void checkFiles() { 

    Task task = new Task(); 
    task.start(); 

    //here I have some Files validation...I don't think it is important to solve the progressbar problem 
    //so it will be ommited 


    //in this point I tried to call update to test the observer solution I found in another post here 
    //task.update(null, null); 

    JOptionPane.showMessageDialog(this, "Done!"); 
    //here the bar jumps from 0% to 100% 

    } 


    private class Task extends Thread implements Observer { 

    public Task() { 
    } 

    //Dont bother with the calculum as I haven't finished working on them.... 
    //The relevant thing here is that it starts a new Thread and I can see the progress 
    //increasing on console using system.out but my progress bar still don't change from 0%. 
    public void run() { 
     int maxSize = 100; 
     final int partsSize = maxSize/listaArquivosSelecionados.size(); 
     while (listFilesValidated.size() != listFilesToValidate.size()) { 
     SwingUtilities.invokeLater(new Runnable() { 
      public void run() { 
      int progress = listFilesValidated.size() * partsSize; 
      System.out.println("Progress" + progress); 
      progressBar.setValue(progress); 

      } 
     }); 
     try { 
      Thread.sleep(100); 
     } 
     catch (InterruptedException e) {} 
     } 
    } 

    //Just tried to set any value to check if it would update before the files validation thread finishes its work. 
    @Override 
    public void update(Observable arg0, Object arg1) { 
     progressBar.setValue(66); 
    } 
} 
+0

您的問題是線程之一 - 您要麼在Swing事件線程上調用長時間運行的代碼,要麼嘗試從Swing事件線程更改進度條的屬性。可能它是第一個而不是第二個,但是無論哪種方式它都必須修復。您必須查看代碼並確保您正確處理Swing線程。查找「Swing中的併發」並研究該系列文章以獲取更多詳細信息以及JProgressBar教程。 –

+1

爲了更好地提供幫助,請發佈[MCVE]或[簡短,獨立,正確的示例](http://www.sscce.org/)。 –

回答

3

您可以創建另一個類進度條(見Oracle tutorial),並使用此:

ProgressBar pbFrame = new ProgressBar(); 
pbFrame.setVisible(true);  
Executors.newSingleThreadExecutor().execute(new Runnable() { 
     @Override 
     public void run() { 
      // run background process 

     } 
    }); 

或者你可以使用SwingWorker,例如:

SwingWorker worker = new SwingWorker<MyReturnType, Void>() { 
    @Override 
    public MyReturnType doInBackground() { 
     // do your calculation and return the result. Change MyReturnType to whatever you need 
    } 
    @Override 
    public void done() { 
     // do stuff you want to do after calculation is done 
    } 
}; 

我有the same question幾年前。

+1

對於[示例](http://stackoverflow.com/a/4637725/230513),您可以從'SwingWorker'的'doInBackground()'方法調用'setProgress()'以供參考。我對你的第一種方法並不樂觀;更多[這裏](http://stackoverflow.com/a/33710937/230513)。 – trashgod