gpt4 book ai didi

Java - 为什么我的 JLabel 图标在执行代码行时没有立即更新?

转载 作者:行者123 更新时间:2023-12-01 09:37:37 25 4
gpt4 key购买 nike

(请原谅我的格式)

我正在使用 JLabel (jLabel3) 作为我正在制作的游戏的背景图像。我有另一个 JLabel (jLabel4) 作为播放器。当玩家到达特定位置时, map (jLabel3) 变为 ("/newpackage/Map2TreasureHunt.png")

我的代码:

if ((x == (66 + 5 * 50)) && (y == (215 + 51))) {

jLabel3.setIcon(new ImageIcon(getClass().getResource("/newpackage/Map2TreasureHunt.png")));
x = 316; //( 66 + 5*50)
y = 11; // y - 4 * 51;

} jLabel4.setLocation(x, y);

我通过 Netbeans 中的“调试”运行此命令,并且图标始终在 if 结束后更新。然后,我尝试了两个 if:

if ((x == (66 + 5 * 50)) && (y == (215 + 51))) {

jLabel3.setIcon(new ImageIcon(getClass().getResource("/newpackage/Map2TreasureHunt.png")));
//x = 316; //( 66 + 5*50)
// y = 11; // y - 4 * 51;

}

if (jLabel3.getIcon().toString().equals("/newpackage/Map2TreasureHunt.png")){
x = 316; //( 66 + 5*50)
y = 11; // y - 4 * 51;
}

JLabel (jLabel3) 在两个 if 运行后更新。

我不太明白这是怎么回事。如果有人知道更有效的方法来重写此代码,那就太好了。

谢谢!-小代码

最佳答案

Swing 中的所有事情都发生在单个线程中:事件调度线程,它基本上执行以下操作:

  1. 等待事件(点击、按键等)
  2. 执行此事件的监听器
  3. 重新绘制需要的内容
  4. 返回 1。

因此,当您仍在对事件使用react的代码中时,不会重新绘制任何内容。推论是,如果您在事件分配线程中无限循环,UI 将完全卡住。

关于Java - 为什么我的 JLabel 图标在执行代码行时没有立即更新?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38727085/

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