为什么在 JFrame 上使用 setLocation() 后我的 ImageIcon 消失了?

问题描述 投票:0回答:1

我想在屏幕上移动包含 GIF 的 JFrame 窗口,但是当我尝试以下操作时:

icon = new ImageIcon(spritePath);
frame.add(new JLabel(icon));
frame.setSize(icon.getIconWidth(), icon.getIconHeight());
frame.setVisible(true);
for (int i = 0; i < screenSize.getWidth() - icon.getIconWidth(); i++) {
    frame.setLocation(i, yMidpoint);
    Thread.sleep(10);
}

我的窗口移动了,但 gif 没有显示。我还尝试将睡眠延迟增加到更高的数字(例如 1000),但这不起作用。当我不使用 setLocation() 移动它时,gif 显示,所以我不确定问题是什么。

java swing jframe imageicon
1个回答
0
投票

我发现问题在于,如果

Thread.sleep()
在创建 JFrame 的同一线程中运行,它会阻止窗口内容被绘制,所以我只是让它在新线程中运行代码,现在它可以工作了。

© www.soinside.com 2019 - 2024. All rights reserved.