progressbar in a thread does not update its UI until the work was done in the main thread

前端 未结 3 1185
北恋
北恋 2020-12-21 18:08

i am cutting a big file into blocks, and want to display the rate of the progress. when i click startCut Button, here is the code to execute:

FileInputStream         


        
3条回答
  •  再見小時候
    2020-12-21 18:46

    The crux of the problem is that you're updating the component: pbCompleteness on a thread other than the Event Dispatch Thread. You can remedy this using SwingUtilities.invokeLater from within your run() method; e.g.

    AtomicInteger value = new AtomicInteger(0);
    while (true) {
      SwingUtilities.invokeLater(new Runnable() {
        public void run() {
          pbCompleteness.setValue(value.get());
        }
      });
    
      // Do some work and update value.
    }
    

    This will cause the JProgressBar to be updated (and repainted) on the Event Dispatch thread as your worker thread continues to run. Note that in order to refer to value within the "inner" anonymous Runnable instance I have changed it to be an AtomicInteger. This is also desirable as it makes it thread-safe.

提交回复
热议问题