using Swing or other “timers” is fine. all of them use System.sleep(1) anyway.
just coming along with more stuff that you dont need for a game-loop. so it’s not “clean” to use them but also totally fine.
on the other hand … imo they’re all wrong. a proper time/clock in java is a pain in the butt. my current approach comes more from measuring and profiling :
public class clock
{
private double hz; // desired fps
private double interval; // nanosec
private double delta; // in millsec
private double start;
private double last;
public double currentHZ; // current fps
public clock(float desiredHZ)
{
this.hz = desiredHZ;
this.inverval = 1.0e9/hz;
}
public void begin()
{
start = (double)System.nanoTime();
delta = ( start - last )*1.0e-6;
currentHZ = 1000f/delta;
last = start;
}
// usually you would use this which yields the same result as using any java Timer class.
public void end()
{
double now = (double)System.nanoTime();
while(now - start < interval)
{
Thread.sleep(1);
now = (double)System.nanoTime();
}
}
// but to get it more precise we can use Thread.yield()
public void endYielding()
{
double now = (double)System.nanoTime();
double t;
while(( t = now - start ) < interval)
{
// switch to expensive yield when remaining sleep time is less then a threshold.
// ideally this would be 1 ms when sleep(1) would actually be a 1 ms sleep, what it never is.
if(( interval - t ) < 1.4e7) Thread.yield(); // magic number 1.4e7, works for me tho. higher = more precise + higher cpu usage
else Thread.sleep(1);
now = System.nanoTime();
}
}
}
in a game loop :
public void init()
{
clock = new clock(45.33f); // 45.33
}
public void update()
{
clock.begin();
// paint things
// swapBuffers
clock.endYielding(); // sleep
System.out.println("current FPS : " + clock.currentHZ);
}
i’m not able to program a more precise timer in java 