Krikke93
Krikke93

Reputation: 101

Java swing Timer loop slows down

So, I'm trying to create a small game using Swing in Java. The game loop I created uses a javax.swing Timer. This timer (normally) calls a loop every 5ms.

Timer tm = new Timer(5, this);
tm.start();

@Override
public void actionPerformed(ActionEvent e) {
    game.tick();
    repaint();
    revalidate();
}

My code can be pretty heavy because it contains quite alot of for-loops, so I'm not surprised this isn't actualy running in a loop every 5ms. Instead, it flows around at a pretty stable 160fps, at least it does on my computer. The moment I tried my game on my brother's computer (less RAM), it at first ran at the same 160fps, but after about 2 minutes the frames drop to a stable 60fps.

I personally find it really weird the frames drop this much at the same time-interval and stays stable like that for the rest of the time.

If anyone encountered a similar problem and knows what is causing it, please let me know. Thanks in advance. ~Krikke

Upvotes: 2

Views: 983

Answers (1)

k_g
k_g

Reputation: 4464

You should use the Timer.scheduleAtFixedRate method instead of the constructor argument.

From the docs (emphasis mine):

In fixed-rate execution, each execution is scheduled relative to the scheduled execution time of the initial execution. If an execution is delayed for any reason (such as garbage collection or other background activity), two or more executions will occur in rapid succession to "catch up." In the long run, the frequency of execution will be exactly the reciprocal of the specified period (assuming the system clock underlying Object.wait(long) is accurate).

As was mentioned in the comments by @HovercraftFullOfEels, you should be making any Swing calls on the Swing Event Thread. For more information, see this tutorial.

Upvotes: 3

Related Questions