如何在Java中使用swing定时器更好地实现动画
我正在使用计时器循环在我的Java应用程序上实现动画。目前,我正在使用与动画相关的静态变量(开始时间、元素从何处开始以及将从何处开始)。有没有更简单的方法?我可以在启动计时器时将这些变量作为参数发送吗如何在Java中使用swing定时器更好地实现动画,java,swing,animation,Java,Swing,Animation,我正在使用计时器循环在我的Java应用程序上实现动画。目前,我正在使用与动画相关的静态变量(开始时间、元素从何处开始以及将从何处开始)。有没有更简单的方法?我可以在启动计时器时将这些变量作为参数发送吗 ... import javax.swing.Timer; public class SlidePuzz2 extends Applet implements MouseMotionListener, MouseListener { ... static Element animati
...
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();
}
}
}
然后,当我想要启动动画时,我所做的就是用ActionListener类的一个新实例作为第二个参数创建一个新计时器,我可以将所有与动画的这一特定部分相关的重要参数传递给构造函数
aniTimer = new Timer(20, new AniTimer(e, board.getBlankPl()));
aniTimer.start();
谢谢Max,我现在开始喜欢Java了 我相信使用
javax.swing.Timer
是实现动画的最好方法。@mre是的,这就是我正在做的。我的问题是如何更好地使用swing计时器,就像更优雅地使用swing计时器一样,避免在动画循环之外使用静态变量来配置它。您不必使用匿名ActionListener。创建实现ActionListener的新类,并使用所有相关/必需的数据对其进行配置。Mwaha,很有趣,谢谢@Max!我将用这个做实验。。。但是,如果有任何指向示例的链接,我将不胜感激,因为我只学了不到一周的Java:)更多示例。+1用于实现ActionListener
。另见。