JFrame freezes during while loop [duplicate]

可紊 提交于 2019-12-10 11:33:02

问题


I am working on a Java program, which reads text files does some probability calculations. Reading files and all related calculations are done in a while loop.

I had created a GUI using JFrame, where i had added a Progress bar (using JProgressBar) to show the progress since the program takes a while to process the files.

The code looks like -

while( there are more files to read )
{
    Read this file ;
    Do calculations ;

    Update progress bar ;
}

Now, the problem is once the while loop starts and the first file is processed, the JFrame simply freezes. The progress bar does not get updated and i cannot press any button in the JFrame. Once the while loop ends the frame is updated and the progress bar is updated to its final value (hence, the progress bar starts from 0 then pauses then finally goes to 100).

Could some one explain why is the JFrame freezing ? Is it possible to update it (progress bar in the JFrame) in the while loop iterations ?

Thanks !


回答1:


You're doing your time intense task in the event dispatch thread (EDT). This is a bad idea as the EDT also updates the UI. Therefore if this thread is blocked no update to the UI is done.




回答2:


The solution is to use threads, that's the reason because you're getting freeze, you're doing everything at the same time.

Please, look:

  • Threads Tutorial
  • Thread Example?



回答3:


A thread can only do one thing at a time. So if you let it do calculations it will not update the gui. So you should use another thread. Also you will probably need to repaint your gui.



来源:https://stackoverflow.com/questions/15788495/jframe-freezes-during-while-loop

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