我正在使用计时器循环在我的Java应用程序上实现动画。目前我正在使用与动画相关的静态变量(开始时间,元素的起点和起始位置)。有更简单的方法吗?我可以在启动计时器时将这些变量作为参数发送吗?
...
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();
...
答案 0 :(得分:1)
感谢@Max的评论,我找到了解决自己问题的方法,在我的主Applet类中创建了一个扩展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();
}
}
}
然后,当我想要开始动画时,我所做的就是创建一个新的Timer,将我的ActionListener类的新实例作为第二个参数,我可以将与此特定动画限制相关的所有重要参数传递给构造函数
aniTimer = new Timer(20, new AniTimer(e, board.getBlankPl()));
aniTimer.start();
谢谢Max,我现在开始喜欢Java了!