[英]How to better implement animation using swing Timer in Java
我正在使用计时器循环在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();
...
感谢@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!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.