简体   繁体   English

Java Swing Timer循环速度变慢

[英]Java swing Timer loop slows down

So, I'm trying to create a small game using Swing in Java. 因此,我正在尝试使用Java中的Swing创建一个小型游戏。 The game loop I created uses a javax.swing Timer. 我创建的游戏循环使用javax.swing计时器。 This timer (normally) calls a loop every 5ms. 此计时器(通常)每5毫秒调用一次循环。

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. 我的代码可能很沉重,因为它包含很多for循环,因此我并不奇怪这并不是每5毫秒一次地在循环中运行。 Instead, it flows around at a pretty stable 160fps, at least it does on my computer. 取而代之的是,它以稳定的160fps每秒流转,至少在我的计算机上如此。 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. 当我在弟弟的计算机上尝试游戏时(较少的RAM),它最初以160fps的速度运行,但是大约2分钟后,帧数下降到了稳定的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 〜Krikke

You should use the Timer.scheduleAtFixedRate method instead of the constructor argument. 您应该使用Timer.scheduleAtFixedRate方法而不是构造函数参数。

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). 从长远来看,执行频率将恰好是指定时间段的倒数 (假设Object.wait(long)底层的系统时钟是准确的)。

As was mentioned in the comments by @HovercraftFullOfEels, you should be making any Swing calls on the Swing Event Thread. 如@HovercraftFullOfEels的评论中所述,您应该在Swing事件线程上进行任何Swing调用。 For more information, see this tutorial . 有关更多信息,请参见本教程

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

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