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);
}
}
非常感谢你的快速和正确的答案。我是SO论坛的新用户,所以我无法对您的答案进行投票,但我会一旦达到15分 – JPC 2014-11-06 12:43:08
@JPC,尽管此答案有效,但持续时间为0的整个KeyFrame是冗余的 - 它不会做任何事情,只要保持矩形就位。您可以安全地删除此KeyFrame。另外,在第二个KeyFrame中,你不需要为'translateYProperty()'设置动画,因为它不会改变。 – 2014-11-06 16:35:50