I did not test this. I don't mean to say that one should do animation this way. I'll let others talk about what is best.
However, for grins, I thought it would still be interesting to see an implementation that does what was requested.
public class SimpleAnimationWithTimer
Image images = new Image;
Timer timer = new Timer();
public volatile int stage;
task = new SimpleAnimationTask();
public void draw(Graphics g, int xLoc, int yLoc)
g.drawImage(images[stage], xLoc, yLoc, null);
public void loadImages(String imagePaths)
public void startWalkAnimation()
timer.schedule(task, 0, 500); }
public void stopWalkAnimation()
class SimpleAnimationTask extends TimerTask
public void run()
stage %= 2; }
Once the class has been initialized and loaded with the two images, to animate it, you would call the startWalkAnimation()
method. The timer local to that object would then flip the state at whatever rate you specify. (I put in 2 changes per second == typical marching tempo.)
The code controlling the main screen would display your pair of images by passing its Graphic object to the draw() method. These draw() calls would be made 60 times per second or at whatever animation rate you are using. For clarity's sake, I put the management of the position of the animation external to its class. Usually if something moves around on the display, you'd put the xLoc & yLoc and movement coding within the object as well, instead of passing the location via the draw() method as done here.
Having a personal Timer is not needed, though. You could also determine the state by a function that is called at the time of display, such as either a calculation based on the current time, or on a count of elapsed frames.
The main issue is how the thread overhead compares to the cost of a method that has to be consulted on a per frame basis. I can see that there might be some appeal to having the code that performs the flip only run a couple times in a given second vs checking whether to flip or not on every
frame. Maybe this isn't a terrible way to do the task.
Some folks might object to using the util timer, due to having to misplaced fears about multi-threading. But the very simple and confined usage here shouldn't cause any problems. The actions are background, not part of the rendering process. The use of the volatile
keyword helps keep the threads properly aligned.