简体   繁体   中英

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

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 .

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