我正在運行一個下載線程(InstallThread)從服務器(60KB)獲取一些文件到文件夾中。每個文件下載完畢後,線程類(InstallThread)改變其percent
字符串變量的當前的進度值。下載另一個線程中的文件,並等待主線程中的進度凍結JFrame渲染
當所有的文件被下載時,done
布爾值被設置爲true。
同時,JPanel的(全球線程上運行),會不斷檢查目前的進展從InstallThread(percent
),並設置一個已經顯示的JLabel,installingLabel
當前百分比文本。
JPanel中也檢查done
變量,這導致while循環停止和應用程序將繼續。
什麼不起作用:當文件被下載,JPanel中沒有任何渲染(無背景色,而選擇JLabel沒有出現,即使啓動while循環之前,標籤是可見的),並且JFrame凍結。
什麼工作:在JFrame中被凍結的文件被下載,而當它done
,JPanel的while循環的休息時間和應用程序繼續運行。
最後,代碼:
FrameDisplay.java#draw_INSTALL(Graphics2D的G2D);(JPanel的延伸級)
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;