【问题标题】:Java TimerTick event for game loop用于游戏循环的 Java Timer Tick 事件
【发布时间】:2011-04-30 21:43:42
【问题描述】:

我尝试使用 java.util.Timer 中的 Timer 在 Java 中制作游戏循环。我无法让我的游戏循环在计时器滴答期间执行。这是这个问题的一个例子。我试图在游戏循环期间移动按钮,但它没有在计时器滴答事件中移动。

import java.util.Timer;
import java.util.TimerTask;
import javax.swing.JFrame;
import javax.swing.JButton;

public class Window extends JFrame {

    private static final long serialVersionUID = -2545695383117923190L;
    private static Timer timer;
    private static JButton button;

    public Window(int x, int y, int width, int height, String title) {

        this.setSize(width, height);
        this.setLocation(x, y);
        this.setTitle(title);
        this.setLayout(null);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setVisible(true);

        timer = new Timer();
        timer.schedule(new TimerTick(), 35);

        button = new JButton("Button");
        button.setVisible(true);
        button.setLocation(50, 50);
        button.setSize(120, 35);
        this.add(button);
    }

    public void gameLoop() {

        // Button does not move on timer tick.
        button.setLocation( button.getLocation().x + 1, button.getLocation().y );

    }

    public class TimerTick extends TimerTask {

        @Override
        public void run() {
            gameLoop();
        }
    }
}

【问题讨论】:

    标签: java swing timer game-loop


    【解决方案1】:

    因为这是一个 Swing 应用程序,所以不要使用 java.util.Timer,而是使用 javax.swing.Timer,也称为 Swing Timer。

    例如,

    private static final long serialVersionUID = 0L;
    private static final int TIMER_DELAY = 35;
    

    在构造函数中

      // the timer variable must be a javax.swing.Timer
      // TIMER_DELAY is a constant int and = 35;
      new javax.swing.Timer(TIMER_DELAY, new ActionListener() {
         public void actionPerformed(ActionEvent e) {
            gameLoop();
         }
      }).start();
    

       public void gameLoop() {
          button.setLocation(button.getLocation().x + 1, button.getLocation().y);
          getContentPane().repaint(); // don't forget to repaint the container
       }
    

    【讨论】:

    • 这是一个相关的example
    • @trashgod:我不会称珍妮特的代码“相关”,因为我的代码不在并且永远不会在同一个联盟中。
    • @Bala:她是 Kleopatra,是 Swing 编码之神,也是SwingX utilities 的作者之一。
    • @Hovercraft Full Of Eels 我刚刚“补充”了我的积分……对你有好处+1 好答案。 :)
    【解决方案2】:

    首先,Timer.schedule 将任务安排为一次执行,而不是重复执行。所以这个程序只能让按钮移动一次。

    还有第二个问题:所有与 swing 组件的交互都应该在事件调度线程中完成,而不是在后台线程中完成。阅读http://download.oracle.com/javase/6/docs/api/javax/swing/package-summary.html#threading 了解更多详情。使用 javax.swing.Timer 以重复的时间间隔执行摆动动作。

    【讨论】:

      猜你喜欢
      • 2014-01-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多