Java 2D Game - Drawing fps on screen

604 views Asked by At

I would like to draw the current FPS on the Canvas.

if(System.currentTimeMillis() - lastTimer >= 1000) {
    lastTimer += 1000;
    System.out.println(ticks+" ticks, "+frames+" fps");
    fps(null, frames);
    frames = 0;
    ticks = 0;
}

public void fps(int frames) {
    BufferStrategy bs = getBufferStrategy();
    if(bs == null) {
        createBufferStrategy(3);
        return;
    }

    Graphics g = bs.getDrawGraphics();

    String strFrames = Integer.toString(frames);
    g.setColor(new Color(128, 128, 128));
    g.setFont(new Font("Arial", Font.PLAIN, 13));
    g.drawString(strFrames, 20, 20);
    bs.show();

}

^^^ This is what I tried, I don't know if it's any good. I just started trying to make games with Java.

public void render() {
    BufferStrategy bs2 = getBufferStrategy();
    if(bs2 == null) {
        createBufferStrategy(3);
        return;
    }

    Graphics g = bs2.getDrawGraphics();

    g.drawImage(image, 0, 0, getWidth(), getHeight(), null);

    g.dispose();
    bs2.show();

}

^^^ I also have this method, maybe it has to be done from there, I don't know.

At the moment it does display the FPS, but flickers, so you only see the value for a split second

1

There are 1 answers

1
Pancheng Xue On

I prefer to use Swing because it's a lot easier to solve your problem. You only need to use setDoubleBuffered(true), see: http://docs.oracle.com/javase/7/docs/api/javax/swing/JComponent.html

If you want to stick with AWT, you need to override the update method to implement doublebuffer, see: http://www.codeproject.com/Articles/2136/Double-buffer-in-standard-Java-AWT