我已经在JFrame的画布上创建了一个小矩形。我已经使该课程成为单身人士(我知道你们中的一些人会说这是不好的做法,但我对此表示满意)。我目前仅在每按一次箭头键时就使用repaint()方法。但是,我现在正在考虑使用一个摆动计时器进行游戏循环。
我创建了一个名为“ GameLoop.java”的类,并添加了以下代码。
public class GameLoop implements ActionListener {
Timer timer = new Timer(10, this);
public void actionPerformed(ActionEvent e) {
timer.start();
GameCanvas.getInstance().repaint();
}
}
但是,当按下箭头时,此操作对屏幕没有任何作用。我有什么想念的/做错了吗?
actionPerformed(ActionEvent e)
仅被称为之后计时器启动,因此不能用于启动计时器。您需要在其他地方启动它。例如:
public class GameLoop implements ActionListener {
GameLoop() {
Timer timer = new Timer(10, this);
timer.start();
}
public void actionPerformed(ActionEvent e) {
GameCanvas.getInstance().repaint();
}
}