0

I am running a Download thread (InstallThread) to get some files from a server (60KB) into a folder. After each file is done downloading, the thread class (InstallThread) changes the value of its percent String variable to the current progress.

When all the files are downloaded, the done boolean is set to true.

Meanwhile, the JPanel (running on the Global thread), constantly checks for the current progress from InstallThread (percent), and sets the text of an already displayed JLabel, installingLabel to the current percentage.

The JPanel also checks for the done variable, which causes the while loop to stop and the application continues.

What doesn't work: While the files are downloading, the JPanel is not rendering anything (no background color, and the JLabel does not appear, even though the label is visible before the while loop is started), and the JFrame freezes.

What works: The files are downloaded while the JFrame is frozen, and when it is done, the JPanel's while loop breaks and the application continues to run.

Finally, the code:

FrameDisplay.java#draw_INSTALL(Graphics2D g2d); (The JPanel-extending class)

installingLabel.setVisible(true);

InstallThread installThread = new InstallThread();
installThread.start();

while (!installThread.done) {
   installingLabel.setText(installThread.percent);
}

/* We continue on with the application */

DotChaser.getInstance().setStage(Stage.MAIN_MENU); 

InstallThread.java

int quota = 62000;
int downloaded = 0;

for (String s : files) { // files is an array with all the files to download
    String url =<The server URL > +s;
    File destination = new File( < The destination folder>+s);

    DownloadThread downloadThread = new DownloadThread(url, destination);
    downloadThread.start(); // DownloadThread is simply downloading the files.

    while (!downloadThread.done) {
        System.out.print("");
    }


    downloaded += destination.length();

    percent = (int) (((double) downloaded / (double) quota) * 100) + "%";
}

done = true;
Kenneth Clark
  • 1,725
  • 2
  • 14
  • 26
Momo
  • 3,542
  • 4
  • 21
  • 34

1 Answers1

3

You're negating all the benefits of using a background thread with code like this:

while (!installThread.done) {
   installingLabel.setText(installThread.percent);
}

as this will completely tie up the Swing event thread, freezing your program.

Instead, use some type of notification system. Myself, I'd use a SwingWorker, add a PropertyChangeListener to the worker and respond to a newValue of SwingWorker.StateValue.DONE. You could use the same PropertyChangeListener to be notified of changes in the SwingWorker's progress property, and use this to update the status of your download.

Please have a look at:

Community
  • 1
  • 1
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373