Search code examples
javaswingawtframe-ratejcomponent

Correctly finding frame rate on a custom Java Component


I am not confident my framerate code is correct, and I have not been able to find exact examples of what I am looking for.

Essentially I have subclassed java.awt.Component, and inside the paint(Graphics) method I call my calculateFrameRate() function, which is shown below. I don't do any incremental drawing in update(). The numbers from this seem high, and I am wondering if the inherent double buffering of the Component class means that paint is being called twice as much as it is being rendered? I'm rusty on the double-buffer stuff though, that may be totally incorrect.

Here is the frame rate method:

 private List<Long> updateTimes = new ArrayList<Long>();

private void calculateFrameRate() {
    long time = System.currentTimeMillis();

    updateTimes.add(new Long(time));

    // We will have the wrong framerate for the first 30 draws. No big.
    float timeInSec = (time - updateTimes.get(0)) / 1000f;

    currentFrameRate_ = 30f / timeInSec;

    if (updateTimes.size() == 31)
        updateTimes.remove(0);

}

Cheers,

Hamy


Solution

  • As an alternative, you could look at System.nanoTime(). This example calculates an average over the preceding number of frames defined by FRAMES.