[英]java swingworker not updating GUI
基本上,問題是我的SwingWorker沒有按照我的意願去做,在這里我將使用一些簡化的代碼示例,這些示例與我的代碼相似,但是沒有討厭的無關緊要的細節。
我有兩節課:
這個想法是MainPanel是一個占位符類,在運行時動態地向它添加了其他JPanel(並刪除了舊的)。
起作用的代碼來自MainPanel類內部:
public void initGalleryPanel() {
this.removeAll();
double availableWidth = this.getSize().width;
double availableHeight = this.getSize().height;
double width = GamePanel.DIMENSION.width;
double height = GamePanel.DIMENSION.height;
double widthScale = availableWidth / width;
double heightScale = availableHeight / height;
final double scale = Math.min(widthScale, heightScale);
add(new GalleryPanel(scale));
revalidate();
repaint();
}
這里的問題是創建GalleryPanel的速度很慢(>一秒鍾),我想顯示一些加載圓圈,並阻止它阻止GUI,所以我將其更改為:
public void initGalleryPanel() {
this.removeAll();
double availableWidth = this.getSize().width;
double availableHeight = this.getSize().height;
double width = GamePanel.DIMENSION.width;
double height = GamePanel.DIMENSION.height;
double widthScale = availableWidth / width;
double heightScale = availableHeight / height;
final double scale = Math.min(widthScale, heightScale);
new SwingWorker<GalleryPanel, Void>() {
@Override
public GalleryPanel doInBackground() {
return new GalleryPanel(scale);
}
@Override
public void done() {
try {
add(get());
} catch (InterruptedException | ExecutionException ex) {
Logger.getLogger(MainPanel.class.getName()).log(Level.SEVERE, null, ex);
}
}
}.execute();
revalidate();
repaint();
}
但是,現在GalleryPanel不再顯示,任何幫助將不勝感激。
額外信息:GalleryPanel的實例創建需要花費很長時間,因為它呈現了實例化時應顯示的內容,因此paintComponent只能繪制該圖像。
問候。
您對revalidate()
和repaint()
調用是在創建或添加GalleryPanel之前立即進行的:
@Override
public void done() {
try {
add(get());
} catch (InterruptedException | ExecutionException ex) {
Logger.getLogger(MainPanel.class.getName()).log(Level.SEVERE, null, ex);
}
}
}.execute();
revalidate();
repaint();
添加新組件后,請嘗試從done()
方法中進行這些調用:
@Override
public void done() {
try {
add(get());
revalidate();
repaint();
} catch (InterruptedException | ExecutionException ex) {
Logger.getLogger(MainPanel.class.getName()).log(Level.SEVERE, null, ex);
}
}
}.execute();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.