我正在使用計時器循環在我的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();
...
我相信使用'javax.swing.Timer'是實現動畫的最佳方式。 – mre 2012-02-07 19:15:55
@mre是的,那就是我現在正在做的。我的問題是如何更好地使用swing Timer,就像避免在動畫循環之外有靜態變量來配置它一樣。 – 2012-02-07 19:19:50
您不必使用匿名ActionListener。創建實現ActionListener的新類,並使用所有相關/必需數據對其進行配置。 – tenorsax 2012-02-07 19:24:18