I didn’t use this on either of my entries because I didn’t realize that it’s smaller than the method I was using until too late, but here’s a template that maintains a relatively steady frame rate and goes easier on your CPU.
import java.applet.Applet;
import java.awt.Event;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
public class G extends Applet implements Runnable {
public void start() {
new Thread(this).start();
}
public void run() {
setSize(800, 600); // For AppletViewer, remove later.
// Set up the graphics stuff, double-buffering.
BufferedImage screen = new BufferedImage(800, 600, BufferedImage.TYPE_INT_RGB);
Graphics g = screen.getGraphics();
Graphics appletGraphics = getGraphics();
// Game loop.
while (true) {
long lastTime = System.nanoTime();
// Update
// TODO add some update logic here.
// Render
g.setColor(Color.black);
g.fillRect(0, 0, 800, 600);
g.setColor(Color.white);
g.drawString("FPS " + String.valueOf(fps), 20, 30);
// Draw the entire results on the screen.
appletGraphics.drawImage(screen, 0, 0, null);
//Lock the frame rate
long delta = System.nanoTime() - lastTime;
if(delta < 20000000L)
{
try
{
Thread.sleep((20000000L - delta) / 1000000L);
}
catch(Exception e)
{
//It's an interrupted exception, and nobody cares
}
}
if (!isActive()) {
return;
}
}
}
public boolean handleEvent(Event e) {
switch (e.id) {
case Event.KEY_PRESS:
case Event.KEY_ACTION:
// key pressed
break;
case Event.KEY_RELEASE:
// key released
break;
case Event.MOUSE_DOWN:
// mouse button pressed
break;
case Event.MOUSE_UP:
// mouse button released
break;
case Event.MOUSE_MOVE:
break;
case Event.MOUSE_DRAG:
break;
}
return false;
}
}
Replace the 20000000L with your desired frame delay.