First of all, 5ms?!? Your game is going at 200FPS!! Try bringing it down to 16ms, 60FPS, that's all you'll ever need.
An Animation class holds an ArrayList of Images and usually has an update(long) method that updates the animation and a getImage() method that returns the current image in the Animation.
In your keyPressed method, you could set a boolean variable to true, so in your Timer, you would call the Animation's update method if that boolean is true, and in your paint method, you would draw the Image returned by the Animation's getImage() method.
Oh and MVC means Model-View-Controller, which basically means you separate the logic from the rendering from the data.
EDIT: Here is a basic Animation class:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
| import java.awt.Image; import java.util.ArrayList;
public class Animation { private ArrayList<Frame> frames; private long totalTime, currentTime; private int frameIndex; public Animation() { frames = new ArrayList<Frame>(); } public void addFrame(Image i, long time) { totalTime += time; frames.add(new Frame(i,totalTime)); } public Image getFrame() { return frames.size() == 0 ? null : frames.get(frameIndex).i; } public void update(long deltaTime) { if(frames.size() > 1) { currentTime += deltaTime; if(currentTime > totalTime) { frameIndex = 0; currentTime %= totalTime; } while(currentTime > frames.get(frameIndex).time) frameIndex++; } } private static class Frame { private Image i; private long time; public Frame(Image i, long time) { this.i = i; this.time = time; } } } |