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