JFrame在while循环期间冻结 [英] JFrame freezes during while loop

查看:88
本文介绍了JFrame在while循环期间冻结的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究Java程序,该程序读取文本文件进行一些概率计算.读取文件和所有相关的计算都是在while循环中完成的.

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.

我使用JFrame创建了一个GUI,在其中添加了一个进度条(使用JProgressBar)以显示进度,因为该程序需要一些时间来处理文件.

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.

代码看起来像-

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

    Update progress bar ;
}

现在,问题是一旦while循环开始并且处理了第一个文件,JFrame就会冻结.进度条没有更新,我无法按JFrame中的任何按钮.当while循环结束时,将更新框架并将进度条更新为其最终值(因此,进度条从0开始,然后暂停,然后最终为100).

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).

有人可以解释为什么JFrame被冻结吗?是否可以在while循环迭代中更新它(JFrame中的进度条)?

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 ?

谢谢!

推荐答案

您正在事件分发线程(EDT)中执行耗时的任务.这是一个坏主意,因为EDT也会更新UI.因此,如果该线程被阻止,则不会完成对UI的更新.

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.

这篇关于JFrame在while循环期间冻结的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆