I can't understand why this Timer is animating jaggedly. Is this a platform-dependent problem? I'm writing a 2D game using this kind of animation and am frustrated with the uneven frame rate. Here's the code for a simplified example:
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import javax.swing.JPanel;
public class AnimationTest extends JPanel
{
private static final long serialVersionUID = 1L;
private Point location = new Point(0, 300);
private int speed = 3;
public AnimationTest()
{
setPreferredSize(new Dimension(800, 600));
}
public void timeStep()
{
move();
repaint();
currentTime = System.nanoTime();
System.out.println(currentTime - previousTime);
previousTime = currentTime;
}
private void move()
{
location.x += speed;
if(location.x >= 800) location.x = 0;
}
@Override
protected void paintComponent(Graphics g)
{
Graphics2D g2d = (Graphics2D) g;
super.paintComponent(g2d);
g2d.fillOval(location.x, location.y, 40, 40);
}
}
And here's the main method:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Timer;
import java.util.TimerTask;
import javax.swing.JFrame;
import javax.swing.WindowConstants;
public class AnimationTestMain
{
public static void main(String[] args)
{
JFrame frame = new JFrame("Test");
final AnimationTest test = new AnimationTest();
frame.add(test);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
int animationMethod = 0;
if(animationMethod == 0)
{
new javax.swing.Timer(10, new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
test.timeStep();
}
}).start();
}
else if(animationMethod == 1)
{
Thread thread = new Thread(new Runnable()
{
@Override
public void run()
{
while(true)
{
test.timeStep();
try
{
Thread.sleep(10);
} catch (InterruptedException e) {}
}
}
});
thread.start();
}
else if(animationMethod == 2)
{
java.util.Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask()
{
@Override
public void run()
{
while(true)
{
test.timeStep();
try
{
Thread.sleep(10);
} catch (InterruptedException e) {}
}
}
}, 0, 10);
}
}
}
Modifying the animationMethod variable doesn't change much of the result. You can see the uneven frame rate in the nanosecond printouts. Help!