gpt4 book ai didi

java swingworker 不更新 GUI

转载 作者:行者123 更新时间:2023-11-29 07:58:19 25 4
gpt4 key购买 nike

基本上,问题是我的 SwingWorker 没有按照我的预期进行,我将在此处使用一些简化的代码示例,它们与我的代码类似,但没有令人讨厌的无关细节。

我有两个类:

  1. MainPanel 扩展 JPanel
  2. 扩展 JPanel 的 GalleryPanel

我的想法是 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 非常慢(> 1 秒),我想显示一些加载圆圈并防止它阻塞 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();

关于java swingworker 不更新 GUI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16133530/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com