简体   繁体   English

坚持使用 Java Swing 定时器

[英]Stuck on using Java Swing Timer

I have created a small rectangle in a canvas which is on a JFrame.我在 JFrame 上的 canvas 中创建了一个小矩形。 I have made the class a singleton (I know some of you will say it's bad practice, but i'm fine with that).我已将 class 设为 singleton(我知道你们中的一些人会说这是不好的做法,但我对此很好)。 I am currently just using the repaint() method whenever an arrow key is pressed.我目前只是在按下箭头键时使用 repaint() 方法。 However, I am now looking at making a Game loop with a swing timer.但是,我现在正在考虑使用 swing 计时器制作游戏循环。

I have created a class called "GameLoop.java" and added the following code.我创建了一个名为“GameLoop.java”的 class 并添加了以下代码。

public class GameLoop implements ActionListener {


    Timer timer = new Timer(10, this);

    public void actionPerformed(ActionEvent e) {

        timer.start();
        GameCanvas.getInstance().repaint();

    }
}

This however, does nothing to the screen when an arrow is pressed.但是,当按下箭头时,这对屏幕没有任何作用。 Is there something I am missing / doing wrong?我有什么遗漏/做错了吗?

The actionPerformed(ActionEvent e) is called only after the timer starts, so it can not be used to start the timer. actionPerformed(ActionEvent e)定时器启动后调用,因此不能用于启动定时器。
You need to start it elsewhere.您需要在其他地方启动它。 For example:例如:

public class GameLoop implements ActionListener {

    GameLoop() {
        Timer timer = new Timer(10, this);
        timer.start();
    }

    public void actionPerformed(ActionEvent e) {
        GameCanvas.getInstance().repaint();
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM