0

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?

  • We'd need to see what is actually updated to tell you want is wrong. How does `GameCanvas` change what is being drawn? – markspace Apr 08 '20 at 23:45
  • Swing is also not a great choice for game type programming, but it appears to be possible if you do extra work. Here's the gory details: https://pavelfatin.com/low-latency-painting-in-awt-and-swing/ – markspace Apr 08 '20 at 23:49
  • You can also search for "java swing pipeline" with other words and get good information: https://docs.oracle.com/javase/10/troubleshoot/java-2d-pipeline-rendering-and-properties.htm – markspace Apr 08 '20 at 23:51
  • Basically, you're problem is, the `Timer` won't start automatically ... and you shouldn't be calling `start` within the `actionPerformed` method. Instead, call `start` as part of some initialisation/setup phase. The "game loop" should also be taking in any input states and modifying the game state before it's painted – MadProgrammer Apr 08 '20 at 23:51

1 Answers1

1

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();
    }
}
c0der
  • 18,467
  • 6
  • 33
  • 65