2016-08-02 106 views
0

(原谅我的格式)Java - 为什么执行代码行时不会立即更新JLabel图标?

我正在使用JLabel(jLabel3)作为我制作的游戏的背景图像。我有另一个JLabel(jLabel4)作为玩家。当玩家到达某个位置时,地图(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 ((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),则既可以更新后,如果我们运行。

我不太明白这里发生了什么。如果有人知道更有效的方式来重写这段代码,那也很好。

谢谢! -littleCode

回答

1

一切都在摇摆发生在一个单独的线程:事件调度线程,基本上执行以下操作:

  1. 等待一个事件(点击,按键等)
  2. 执行此事件的监听器
  3. 重绘什么需要是
  4. 回到1

所以,当你仍然在代码中对事件做出反应时,没有东西会被重新绘制。推论是,如果你在事件dipatch线程中无限循环,UI将完全冻结。