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;