【问题标题】:Alternate 2 images in Java Game with timer使用计时器在 Java 游戏中交替 2 个图像
【发布时间】:2012-09-15 13:35:08
【问题描述】:

我正在用 Java 做一个简单的游戏。 我有一个名为“Drawer”的类,每 50 毫秒重新绘制一次保存在 BufferedImages 数组中的图像。

我有一个方法可以在Player Class中将播放器转换成一个巨大的播放器,代码是:

    public void playerEvolution() {
    for (int i = 0; i < 5; i++) {
        this.setImageIndex(15);
        try {
            Thread.sleep(500);
            this.setImageIndex(17);
            Thread.sleep(500);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    this.isHuge();
}

我希望每 0.5 秒交替 2 张图像,但在 GamePanel 中不交替任何图像,并且仅在花费 2.5 秒(0.5 * 5 循环)时出现最终图像。

有什么想法吗??

【问题讨论】:

    标签: java image swing timer alternate


    【解决方案1】:

    如果这是一个 Swing 应用程序(你没有说),请使用 javax.swing.Timer 或 Swing Timer。永远不要在主 Swing 事件线程(称为事件调度线程或 EDT)上调用 Thread.sleep(...)。在 Timer 的 ActionListener 中有一个 int count 变量,每次调用 actionPerformed(...) 时都会递增,如果计数 > 到最大计数(这里是 5 * 2,因为你来回交换),则停止 Timer。

    例如,

    public void playerEvolution() {
      int delay = 500; // ms
      javax.swing.Timer timer = new javax.swing.Timer(delay , new ActionListener() {
         private int count = 0;
         private int maxCount = 5;
    
         @Override
         public void actionPerformed(ActionEvent evt) {
            if (count < maxCount * 2) {
               count++;
               // check if count is even to decide 
               // which image to use, and then
               // do your image swapping here
            } else {
               ((javax.swing.Timer)evt.getSource()).stop();
            }
         }
      });
    }
    

    【讨论】:

      【解决方案2】:
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多