Set program to 60FPS, but runs at 120FPS?

蹲街弑〆低调 提交于 2019-12-13 04:39:48

问题


I have a problem that puzzles me. I have this small application that creates a JFrame that should update the graphics at the desired fps. But when I start the application, it runs at 120 fps instead of 60 fps. If I set fps = 30, it runs at 60fps, if fps =60, it runs at 120fps, and so on (to measure the fps I use FRAPS).

Here's the 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)
    {
    }
}

The Timer sets the program at 60fps as desired, but it actually draws 30 fps, repeating each frame twice. The paintComponent() is painting twice each time repaint() is called. How can I change it to just paint once? Thanks in advance.

来源:https://stackoverflow.com/questions/10473637/set-program-to-60fps-but-runs-at-120fps

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!