如何设置具有刷新率的 JFrame?

2022-01-24 00:00:00 java jframe

我有一个 2d 游戏,除了图形之外,整个结构都是完全编码的.我只是更新一个 JFrame 的单个组件,它是一个包含 50 个图像的图形.每一帧图像都位于不同的位置,因此需要刷新率.

I have a 2d game which the entire structure is completely coded except the graphics. I am just updating the single component of a JFrame which is a Graphic containing 50 images. Each frame the images are in a different location hence the need for a refresh rate.

为了绘制,我重写了 paintComponent() 方法,所以我真正需要做的就是每 40 毫秒重新绘制一次组件(同样,它只是一个图形).

To paint, I have overridden the paintComponent() method, so all I really need to do is repaint the component (which, again, is just a Graphic) every 40ms.

如何设置 25FPS 的 JFrame?

How do you set up a JFrame with 25FPS?

推荐答案

这个 AnimationTest 使用 javax.swing.Timer.40 ms 的周期将产生 25 Hz 的速率.

This AnimationTest uses javax.swing.Timer. A period of 40 ms would give a rate of 25 Hz.

private final Timer timer = new Timer(40, this);

附录:计时器的 ActionListener 通过调用 repaint() 进行响应,随后调用您重写的 paintComponent() 方法

Addendum: The timer's ActionListener responds by invoking repaint(), which subsequently calls your overridden paintComponent() method

@Override
public void actionPerformed(ActionEvent e) {
    this.repaint();
}

相关文章