66fps - 88fps.
Trick?
When you set up a Window ALWAYS use:
SwingUtilities.invokeLater
(
new Runnable()
{
public void run()
{
doWindowSwingInit();
}
}
);
I was using J2D.
Code:
private static Main instance;
private BufferStrategy bs;
private Graphics2D g;
//game
private GameStart game;
private int fps;
private void loop()
{
g = (Graphics2D)bs.getDrawGraphics();
g.clearRect(0, 0, getWidth(), getHeight());
//logic
game.logic();
//rendering
game.render(g);
//print fps in bottom corner
g.setColor(Color.BLACK);
g.drawString("FPS:" + fps, 15, getHeight() - 15);
bs.show();
g.dispose();
}
/** Creates a new instance of Main */
public Main()
{
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(640, 480);
this.setLocationRelativeTo(null);
this.setLocation(getX() - 100, getY() - 100);
this.setIgnoreRepaint(true);
this.setResizable(false);
this.addKeyListener(new Input());
this.setVisible(true);
this.createBufferStrategy(3);
bs = this.getBufferStrategy();
g = (Graphics2D)bs.getDrawGraphics();
}
private void initGame()
{
game = new GameStart();
}
/**
* @param args the command line arguments
*/
public static void main(String[] args)
{
SwingUtilities.invokeLater
(
new Runnable()
{
public void run()
{
instance = new Main();
}
}
);
instance.initGame();
long cTime, eTime;
while(true)
{
if( instance.isFocusOwner() )
{
cTime = System.nanoTime();
//added to limit framerate
instance.pause();
//limiter
instance.loop();
eTime = System.nanoTime() - cTime;
instance.fps = (int)(1000000000/eTime);
}
instance.pause();
}
}
private void pause()
{
try
{
Thread.sleep(10);
}catch(InterruptedException e)
{
e.printStackTrace();
}
}
private class Input implements KeyListener
{
public void keyPressed(KeyEvent e)
{
switch( e.getKeyCode() )
{
case KeyEvent.VK_ESCAPE:
System.exit(0);
break;
}
}
public void keyTyped(KeyEvent ee)
{
}
public void keyReleased(KeyEvent eeee)
{
}
}
public static int getResWidth()
{
if( instance == null )
return 0;
return instance.getWidth();
}
public static int getResHeight()
{
if( instance == null )
return 0;
return instance.getHeight();
}