Consider the following Swing timer :
timer = new Timer (ballSpeed, tc);
ballSpeed is initially at 10. tc is an Action Listener class that increments the x value of an object painted on the screen. The variable ballSpeed is kind of a misnomer because the lower the value, the faster the object moves.
Now I want the object’s movement to look as smooth as possible. Therefore I will only increment the x value one by one in the ActionListener. That is the object should only move move pixel by pixel. I use x++ instead of x+=10. Therefore I will not modify the ball’s speed this way.
Now since the first argument of Timer will only accept an integer, it doesn’t give me a great deal of control over the object’s speed. I can only use 10,9,8,etc. The object either moves too fast or too slow.
To summarize, millisecond precision is not sufficient.
Is there a way around this? Or is there an overall better way to implement object movement on the screen?
A
javax.swing.Timerdoes not have sufficient accuracy or precision to generate the smooth graphics you are trying to achieve. Furthermore, the swing timer is affected by anything else in the swing event queue:If you don’t want to use some media framework or use APIs that describe the motion of objects (rather than actually moving the objects), you should use the swing timer as a way to schedule the next computation, but determine the time elapsed since last computation by looking at the difference between
System.nanoTime()now and the nanoTime during the last computation.Using this approach, you will have more jaggered but more correct animation on underpowered machines.