Reputation: 1803
I am using a timer loop to implement animation on my Java app. At the moment I am using static variables that relate to the animation (the start time, where the element's starting from and where it's going to). Is there a simpler way to do this? Can I send these variables as arguments when I start the timer instead?
...
import javax.swing.Timer;
public class SlidePuzz2 extends Applet implements MouseMotionListener, MouseListener {
...
static Element animating;
static PieceLoc blank;
static int delta;
static int orig_x;
static int orig_y;
static long timeStart;
Timer aniTimer;
...
public void init() {
...
aniTimer = new Timer(20, new ActionListener() {
public void actionPerformed(ActionEvent evt) {
int dx = (blank.x*piece-orig_x);
int dy = (blank.y*piece-orig_y);
int t = 200;
delta = (int)(System.currentTimeMillis()-timeStart);
if (delta>t) delta=t;
animating.x = orig_x + dx*delta/t;
animating.y = orig_y + dy*delta/t;
repaint();
if (delta==t) {
animating.updateCA();
board.checkCompleted();
aniTimer.stop();
}
}
});
...
setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
blank = board.getBlankPl();
animating = e;
timeStart = System.currentTimeMillis();
orig_x = animating.x;
orig_y = animating.y;
aniTimer.start();
...
Upvotes: 2
Views: 1725
Reputation: 1803
Thanks to comments by @Max I have found a solution to my own problem, creating an inner class inside my main Applet class that extends ActionListener.
public class AniTimer implements ActionListener {
Element animating;
PieceLoc blank;
int orig_x;
int orig_y;
long timeStart;
int delta;
public AniTimer(Element e, PieceLoc pl) {
animating = e;
blank = pl;
orig_x = animating.x;
orig_y = animating.y;
timeStart = System.currentTimeMillis();
}
public void actionPerformed(ActionEvent evt) {
int dx = (blank.x*piece-orig_x);
int dy = (blank.y*piece-orig_y);
int t = 200;
delta = (int)(System.currentTimeMillis()-timeStart);
if (delta>t) delta=t;
animating.x = orig_x + dx*delta/t;
animating.y = orig_y + dy*delta/t;
repaint();
if (delta==t) {
aniTimer.stop();
animating.updateCA();
board.checkCompleted();
}
}
}
Then when I want to start the animation all I do is make a new Timer with a new instance of my ActionListener class as the second argument and I can pass all the vital arguments relating to just this particular stint of animation to the constructor.
aniTimer = new Timer(20, new AniTimer(e, board.getBlankPl()));
aniTimer.start();
Thanks Max, I'm starting to love Java now!
Upvotes: 1