用于游戏循环的 Java TimerTick 事件 [英] Java TimerTick event for game loop
本文介绍了用于游戏循环的 Java TimerTick 事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我尝试使用 java.util.Timer 中的 Timer 在 Java 中制作游戏循环.我无法在计时器滴答期间执行我的游戏循环.下面是这个问题的一个例子.我试图在游戏循环期间移动按钮,但它没有在计时器滴答事件上移动.
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. I am trying to move the button during the game loop, but it is not moving on the timer tick event.
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();
}
}
}
推荐答案
由于这是一个 Swing 应用程序,所以不要使用 java.util.Timer,而是使用 javax.swing.Timer,也称为 Swing Timer.
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.
例如
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
}
这篇关于用于游戏循环的 Java TimerTick 事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文