Glad to help
For the game loops, I recommend the time step loop. Here is my implementation:
final int FPS = 60;
int currentFPS = 0;
int frames = 0;
long time = System.nanoTime();
long lastTime = System.nanoTime();
while(isRunning) {
long now = System.nanoTime();
long diffTime = now-lastTime;
//update loop. to prevent certain problems when deltaTime is a large number, max deltaTime is 1000000000/FPS
while(diffTime > 0) {
long rem = diffTime%(1000000000/FPS);
long deltaTime = (rem == 0 ? 1000000000/FPS : rem);
update(deltaTime);
diffTime -= deltaTime;
}
lastTime = now;
//to calculate FPS
if(System.nanoTime()-time >= 1000000000) {
time = System.nanoTime();
currentFPS = frames;
frames = 0;
}
//render graphics
render();
//sleeping in an active loop until the desired sleep time has passed
try {
if(FPS > 0) {
long sleepTime = Math.round((1000000000.0/FPS)-(System.nanoTime()-lastTime));
if(sleepTime <= 0)
continue;
long prevTime = System.nanoTime();
while(System.nanoTime()-prevTime <= sleepTime) {
Thread.yield();
Thread.sleep(1);
}
}
}
catch(Exception exc) {
exc.printStackTrace();
}
}
EDIT: If you are going to use BufferStrategy for drawing on a Canvas, here is the recommended render() method:
public void render() {
try {
do {
do {
Graphics2D g = (Graphics2D)strategy.getDrawGraphics();
//draw your game
g.dispose();
}while(strategy.contentsRestored());
strategy.show();
}while(strategy.contentsLost());
}
catch(Exception exc) {
exc.printStackTrace();
}
}