Refresh Swing GUI

允我心安 提交于 2019-12-11 19:48:43

问题


I have a Board that contains tiles and the Tiles contain Obstacles. An obstacle can be one of the several types (wall, laser, ...).

Every round of the game I execute the board, which exectutes all the Obstacles. Once an obstacle has been executed and something has changed the GUI is notified and the affected tiles are refreshed.

In the GUI a tile is an OverLayLayout that contains overlapping images (JLabels), so all the overlapping images are visible.

Now the problem is when I execute them, it goes to fast, you can't anything happen. E.g. you don't see the laser beam appear, the player will be damaged but you didn't see it happen...

So I tried to let the game wait for e.g. 500ms so the user can see the GUI update. I've tried (but might have done it wrong): timers, swingtimers, countdownlatch, ... but I can't seem to get it to work. Any ideas on how to fix this? Or maybe an alternative for the waiting?

Thanks in advance!

Update: The execute in board looks like this:

Iterator<Obstacle> it = obstacles.iterator();
while (it.hasNext())
    it.next().execute(this);

CountDownLatch countDown = new CountDownLatch(1);
setChanged();
notifyObservers(countDown);
countDown.await();

The update function of the GUI board (which is notified) looks like this:

final CountDownLatch countDown = (CountDownLatch) arg;
SwingUtilities.invokeLater(new Runnable(){
   public void run() {
      try {
        updateUI();
        wait(500);
      } catch (InterruptedException ex) { }
            countDown.countDown();
   }
});

回答1:


Without seeing your code, it's hard to identify the problem; I suspect you're blocking the event dispatch thread.

This tile-based game uses an instance of javax.swing.Timer to animate play. Press A to enable animation, and click on a free square to see the effect. You may be able adapt the approach to your game.



来源:https://stackoverflow.com/questions/10726034/refresh-swing-gui

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!