2015-06-14 63 views
0

我正在運行一個下載線程(InstallThread)從服務器(60KB)獲取一些文件到文件夾中。每個文件下載完畢後,線程類(InstallThread)改變其percent字符串變量的當前的進度值。下載另一個線程中的文件,並等待主線程中的進度凍結JFrame渲染

當所有的文件被下載時,done布爾值被設置爲true。

同時,JPanel的(全球線程上運行),會不斷檢查目前的進展從InstallThreadpercent),並設置一個已經顯示的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; 

回答

3

你否定使用後臺線程下面類似的代碼的所有優點:

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

,因爲這將完全佔用了Swing事件線程,凍結你的程序。

相反,使用某種類型的通知系統。我自己,我會使用SwingWorker,給工作人員添加PropertyChangeListener並響應SwingWorker.StateValue.DONE的新值。您可以使用相同的PropertyChangeListener來通知SwingWorker的progress屬性中的更改,並使用它來更新下載的狀態。

請看看:

相關問題