2014-11-06 108 views
1

我一直堅持這最近幾個小時這個愚蠢的錯誤。基本上,我想動畫(幻燈片)的小矩形,直到我點擊框中的鼠標(X值是我現在所關心的)。下面的來源完全是這樣。動畫矩形形狀的鼠標距離點擊數:

但是,我真正想要的是保存終點的位置,這樣如果我點擊窗格的中點,該框會滑到中途點(如上所述),那麼如果我要點擊方式的3/4,方塊將從中點滑動到3/4點。

看來我們所要做的就是setX(),對吧?取消註釋保存矩形X座標的位置並重新運行。你會看到它跳躍!爲什麼?我完全沒有線索,一直在試圖找到一個修復/解決方法,爲這個討厭的bug在過去的幾個小時裏變得無處可尋。如果有人能指出我正確的方向,我會向前付款,我保證。

import javafx.animation.KeyFrame; 
import javafx.animation.KeyValue; 
import javafx.animation.Timeline; 
import javafx.application.Application; 
import javafx.scene.Scene; 
import javafx.scene.input.MouseEvent; 
import javafx.scene.layout.Pane; 
import javafx.scene.shape.Rectangle; 
import javafx.stage.Stage; 
import javafx.util.Duration; 

public class TimelineEvents extends Application { 

    Rectangle myRectangle; 

    public void start(Stage primaryStage) { 
     Pane mainPane = new Pane(); // Create a ball pane 
     //ballPane.play(); 
     Scene scene = new Scene(mainPane, 500, 500); 
     primaryStage.setScene(scene); 
     primaryStage.show(); 

     myRectangle = new Rectangle(0, 20, 30, 30); 

     mainPane.setOnMouseClicked((MouseEvent event) -> { 
      animate(event); 
     }); 

     mainPane.getChildren().add(myRectangle); 
    } 

    public void animate(MouseEvent event) { 

     Timeline timeline = new Timeline(); 
     System.out.println(myRectangle.getY()); 
     timeline.getKeyFrames().addAll(
       new KeyFrame(Duration.ZERO, 
         new KeyValue(myRectangle.translateXProperty(), 0), 
         new KeyValue(myRectangle.translateYProperty(), 0) 
       ), 
       new KeyFrame(new Duration(1000), 
         new KeyValue(myRectangle.translateXProperty(), event.getX()), 
         new KeyValue(myRectangle.translateYProperty(), 0) 
       ) 
     ); 

     timeline.play(); 

     timeline.setOnFinished((ActionEvent) -> { 
      //myRectangle.setX(event.getX()); 
     }); 
    } 

    public static void main(String[] args) { 
     launch(args); 
    } 
} 

回答

0

你總是開始動畫在零的位置,改變這樣的動畫:

timeline.getKeyFrames().addAll(
     new KeyFrame(Duration.ZERO, 
     new KeyValue(myRectangle.translateXProperty(), myRectangle.getTranslateX()), 
      new KeyValue(myRectangle.translateYProperty(), 0) 
    ), 
.... 

編輯: 結合的評論,你需要的是

timeline.getKeyFrames().add(
     new KeyFrame(new Duration(1000), 
       new KeyValue(myRectangle.translateXProperty(), event.getX()) 
     ) 
); 
+0

非常感謝你的快速和正確的答案。我是SO論壇的新用戶,所以我無法對您的答案進行投票,但我會一旦達到15分 – JPC 2014-11-06 12:43:08

+0

@JPC,儘管此答案有效,但持續時間爲0的整個KeyFrame是冗餘的 - 它不會做任何事情,只要保持矩形就位。您可以安全地刪除此KeyFrame。另外,在第二個KeyFrame中,你不需要爲'translateYProperty()'設置動畫,因爲它不會改變。 – 2014-11-06 16:35:50