坚持使用Java Swing Timer

我在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();

    }
}

但是,当按下箭头键时,这对屏幕没有任何作用。我有什么想念的/做错了吗?

ahuo1987 回答:坚持使用Java Swing Timer

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();
    }
}
本文链接:https://www.f2er.com/2481633.html

大家都在问