简体   繁体   English

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

[英]Java - Why doesn't my JLabel icon update instantly when the line of code is executed?

(excuse my formatting) (请问我的格式)

I'm using a JLabel (jLabel3) as a background image for a game I am making. 我正在使用JLabel(jLabel3)作为我正在制作的游戏的背景图像。 I have another JLabel (jLabel4) as the player. 我还有另一个JLabel(jLabel4)作为播放器。 When the Player reaches a certain position, the map (jLabel3) changes to ("/newpackage/Map2TreasureHunt.png") . 当播放器到达某个位置时,地图(jLabel3)更改为("/newpackage/Map2TreasureHunt.png")

My code: 我的代码:

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);

I ran this through Debug in Netbeans, and the icon is always updated after the if ends. 我通过Netbeans中的Debug来运行此命令,并且if结束后,该图标始终会更新。 Then, I tried two if's: 然后,我尝试了两个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;
    }

The JLabel (jLabel3) then updates after BOTH if's run. 然后,如果同时运行,则JLabel(jLabel3)会同时更新。

I don't quite understand what is going on here. 我不太了解这里发生了什么。 If someone knows a more efficient way to rewrite this code, that would also be nice. 如果有人知道更有效的方法来重写此代码,那也很好。

Thanks! 谢谢! -littleCode -littleCode

Everything in Swing happens in a single thread: the event dispatch thread, which basically does the following: Swing中的所有事件都在单个线程中发生:事件分发线程,该线程基本上执行以下操作:

  1. wait for an event (click, key press, etc.) 等待事件(单击,按键等)
  2. execute the listeners for this event 执行此事件的侦听器
  3. repaint what needs to be 重新粉刷需要的东西
  4. go back to 1. 回到1。

So, while you're still inside the code reacting to an event, nothing will be repainted. 因此,尽管您仍在代码中对事件做出反应,但不会重绘任何内容。 The corollary is that, if you loop infinitely in the event dipatch thread, the UI will completely freeze. 必然的结果是,如果您在事件dipatch线程中无限循环,则UI将完全冻结。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM