java jprogressbar hangs during heavy operation

醉酒当歌 提交于 2019-12-04 06:01:57

问题


I'm writing a java program and, before I call a method that makes heavy use of the CPU, I display a frame with a JProgressBar on it. Although I display it before the method is called, the JProgressBar is not shown until the method is over. The progress bar does not interact with the method in any way (yet) and that's why I am confused. It is something like:

progressbarframe.setVisible(true); // it is a indeterminate progress bar
heavyLoadMethod();
progressbarframe.dispose();

The frame shows, but the progress bar doesn't initialize during the method. Is there any way I can solve this without using threads? What would be the simplest way?

Thank you for your time


回答1:


You should call the heavyLoadMethod in a separate thread. You can use a java.util.concurrent.Executor for it:

Executor executor = java.util.concurrent.Executors.newSingleThreadExecutor();
executor.submit(new Runnable() { public void run() { heavyLoadMethod();}});

Now the method will be called in a separate thread and the progress bar will be displayed properly.




回答2:


You are blocking the EDT from repainting the GUI.

Read the section from the Swing tutorial on Concurrency in Swing for a full explanation of the problem.

Also, read the section on "How to Use Progress Bars" for a working example.



来源:https://stackoverflow.com/questions/3652743/java-jprogressbar-hangs-during-heavy-operation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!