[英]Swing GUI doesn't update during data processing
我有一個問題,我的Swing GUI組件在程序繁忙時沒有為我更新。 我正在創建一個圖像編輯器,並且在進行繁重的處理時,我嘗試更改“狀態”標簽,同時使用戶知道發生了什么。 標簽直到處理完成后才會更新。
如何立即更新標簽,而不必等待? 順便說一下,我的標簽都放在了JPanel上。
在for循環和以下方法完成之前,不會設置我的標簽。
labelStatus.setText("Converting RGB data to base 36...");
for (int i = 0; i < imageColors.length; i++) {
for (int j = 0; j < imageColors[0].length; j++) {
//writer.append(Integer.toString(Math.abs(imageColors[i][j]), 36));
b36Colors[i][j] = (Integer.toString(Math.abs(imageColors[i][j]), 36));
}
}
String[][] compressedColors = buildDictionary(b36Colors);//CORRECTLY COUNTS COLORS
我有一個問題,我的Swing GUI組件在程序繁忙時沒有為我更新。
那是因為您正在Event Dispatch Thread (EDT)
上執行長時間運行的任務,並且GUI在任務完成執行之前無法重新繪制自身。
您需要在單獨的線程或SwingWorker中執行長時間運行的任務(以獲得更好的解決方案)。 閱讀Swing 並發教程中的這一節,以獲取有關EDT
更多信息以及使用SwingWorker防止此問題的示例。
你可以做這樣的事情,不是最好的,但是它可以給你一些想法
創建一個線程調度程序類,並從主類中調用它
public class ThreadDispatcher implements Runnable {
public ThreadDispatcher() {
}
public void run() {
//call the method related heavy process here
}
}
在你的主要班級可能就是這樣
Thread thread = new Thread(new ThreadDispatcher());
thread.start();
sleep(100);
趕上InterruptedException ex。
並檢查Java線程示例。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.