[英]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.