简体   繁体   中英

Stuck on using Java Swing Timer

I have created a small rectangle in a canvas which is on a JFrame. I have made the class a singleton (I know some of you will say it's bad practice, but i'm fine with that). I am currently just using the repaint() method whenever an arrow key is pressed. However, I am now looking at making a Game loop with a swing timer.

I have created a class called "GameLoop.java" and added the following code.

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.
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();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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