2012-02-07 76 views
2

我正在使用計時器循環在我的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(); 
... 
+3

我相信使用'javax.swing.Timer'是實現動畫的最佳方式。 – mre 2012-02-07 19:15:55

+0

@mre是的,那就是我現在正在做的。我的問題是如何更好地使用swing Timer,就像避免在動畫循環之外有靜態變量來配置它一樣。 – 2012-02-07 19:19:50

+6

您不必使用匿名ActionListener。創建實現ActionListener的新類,並使用所有相關/必需數據對其進行配置。 – tenorsax 2012-02-07 19:24:18

回答

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(); 
     } 
    } 
} 

然後當我要開始動畫我要做的就是讓一個新的計時器與我的ActionListener類的新實例作爲第二個參數,我可以通過所有涉及的只是這個特殊限制的重要參數動畫給構造函數。

aniTimer = new Timer(20, new AniTimer(e, board.getBlankPl())); 
aniTimer.start(); 

Thanks Max,我現在開始愛上Java了!

+0

+1。另見[*如何使用操作*](http://docs.oracle.com/javase/tutorial/uiswing/misc/action.html)。 – trashgod 2012-02-25 07:24:26