updating a JProgressBar while processing

[亡魂溺海] 提交于 2019-12-01 19:25:29

You MUST update the JProgress bar on the Swing Event Dispatch Thread. You cannot modify Swing components on any other thread.

Your only other alternative would be to set the JProgress bar "indeterminate" before you start your thread where the progress bar will just go back and forth.

E.g

progBar.setIndeterminate(true);

See the SwingWorker javadoc: http://docs.oracle.com/javase/6/docs/api/javax/swing/SwingWorker.html

If you don't want to use the SwingWorker, another option is the SwingUtilities.invokeLater method

//inside your long running thread when you want to update a Swing component
SwingUtilities.invokeLater(new Runnable() {
    public void run() {

        //This will be called on the EDT
        progressBar.setValue(progressBar.getValue() + 1);


    }
});

In addition to the code provided by @btantlinger, I found after testing that it required an additional line of code in order to update the progress bar on the UI thread while processing. See below.

   SwingUtilities.invokeLater(new Runnable() {
       public void run() {
       progressBar.setValue((int)percentage);
       //below code to update progress bar while running on thread
       progressBar.update(progressBar.getGraphics());}
     });   
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!