我有一个令我困惑的问题。我有这个小应用程序,它创建一个 JFrame,它应该以所需的 fps 更新图形。但是当我启动应用程序时,它以 120 fps 而不是 60 fps 运行。如果我设置 fps = 30,它以 60fps 运行,如果 fps =60,它以 120fps 运行,依此类推(为了测量我使用 FRAPS 的 fps)。
这是SSCCE:
import java.awt.*;
import javax.swing.*;
public class Controller
{
public static TheFrame window;
public static long time = 0;
public static boolean funciona = true;
public static int fps = 60;
public static int x;
public static void main(String [] args)
{
window = new TheFrame();
while(funciona) {
time = System.nanoTime();
window.Redraw();
time = System.nanoTime() - time;
try {Thread.sleep( (1000/fps) - (time/1000000) );} catch (Exception e){}
}
}
}
class TheFrame
{
public JFrame theFrame;
public CanvasScreen canvas;
public TheFrame()
{
canvas = new CanvasScreen();
theFrame = new JFrame();
theFrame.setSize(1280, 720);
theFrame.setContentPane(canvas);
theFrame.setUndecorated(true);
theFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
theFrame.setVisible(true);
}
public void Redraw()
{
theFrame.repaint();
}
}
class CanvasScreen extends JComponent
{
public void paintComponent(Graphics g)
{
}
}
计时器根据需要将程序设置为 60 fps,但它实际上绘制 30 fps,每帧重复两次。每次调用 repaint() 时,paintComponent() 都会绘制两次。如何将其更改为仅绘制一次?提前致谢。