Java TimerTick event for game loop

后端 未结 2 1161
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-21 05:25

I tried making a game loop in Java using the Timer from java.util.Timer. I am unable to get my game loop to execute during the timer tick. Here is an example of this issue.

2条回答
  •  庸人自扰
    2020-12-21 05:43

    Since this is a Swing application, don't use a java.util.Timer but rather a javax.swing.Timer also known as a Swing Timer.

    e.g.,

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

    in the constructor

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

    and

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

提交回复
热议问题