2

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 !

mre
  • 43,520
  • 33
  • 120
  • 170
Ankit Rustagi
  • 5,539
  • 12
  • 39
  • 70

3 Answers3

3

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.

Uwe Plonus
  • 9,803
  • 4
  • 41
  • 48
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:

Community
  • 1
  • 1
Castiblanco
  • 1,200
  • 4
  • 13
  • 32
  • not incorrect, but not the whole story either: all swing-view-related access must happen on a particular thread, the ominous EDT :-) – kleopatra Apr 03 '13 at 14:19
1

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.

WereWolfBoy
  • 498
  • 1
  • 4
  • 23