[英]How to animate a button with Timeline?
我想为按钮设置动画。 我要使其单击后更改其位置。 我写了这样的代码,但是不起作用。 在这种情况下,控制台中不会出现任何错误。 该按钮只是不响应按下。
double stopPosition = 100;
KeyValue kk2 = new KeyValue(btn.layoutXProperty(), stopPosition, Interpolator.LINEAR);
KeyFrame kk = new KeyFrame(Duration.millis(5000),kk2);
Timeline timeline = new Timeline();
timeline.getKeyFrames().add(kk);
timeline.setCycleCount(1);
btn.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
System.out.println("Hello World!");
timeline.play();
}
});
我究竟做错了什么?
我假设您将按钮放置在某种布局中,以便进行定位。 如果您修改layoutX
则意味着在下一次布局传递期间, Button
会简单地由父布局放回“它所属的位置”。
如果要移动Button
,则应选择其他布局作为父级,或改为使用translateX
属性。 translateX
将Button
相对于父布局将其放置的位置( layoutX
)移动。
您应该设置平移坐标的动画,而不是布局坐标的动画。
double deltaPosition = 100; //translation gets added to your current layoutX
KeyValue kk2 = new KeyValue(btn.translateXProperty(), deltaPosition, Interpolator.LINEAR);
KeyFrame kk = new KeyFrame(Duration.millis(5000),kk2);
Timeline timeline = new Timeline();
timeline.getKeyFrames().add(kk);
timeline.setCycleCount(1);
btn.setOnAction(ae -> {
System.out.println("Hello World!");
timeline.play();
}
);
布局值会被诸如HBox
, AnchorPane
类的布局窗格覆盖,但不会被Group
或Pane
覆盖。 或者,在按钮上设置setManaged(false)
,以便父容器不会干扰其布局,但是,您必须自己进行所有布局。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.