简体   繁体   English

如何使用时间轴为按钮制作动画?

[英]How to animate a button with Timeline?

I want to animate a button. 我想为按钮设置动画。 I want to make it change its position after clicking on it. 我要使其单击后更改其位置。 I wrote such code, but it does not work. 我写了这样的代码,但是不起作用。 In this case, no errors appear in the console. 在这种情况下,控制台中不会出现任何错误。 The button simply does not respond to pressing. 该按钮只是不响应按下。

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

What am I doing wrong? 我究竟做错了什么?

I assume you placed the button in some layout that takes care of positioning. 我假设您将按钮放置在某种布局中,以便进行定位。 If you modify layoutX this means during the next layout pass the Button is simply put back "where it belongs" by the parent layout. 如果您修改layoutX则意味着在下一次布局传递期间, Button会简单地由父布局放回“它所属的位置”。

If you want to move the Button , you should choose a different layout as parent or use the translateX property instead. 如果要移动Button ,则应选择其他布局作为父级,或改为使用translateX属性。 translateX moves the Button relative to the position where the parent layout places it ( layoutX ). translateXButton相对于父布局将其放置的位置( layoutX )移动。

You should animate translation coordinates, not layout coordinates. 您应该设置平移坐标的动画,而不是布局坐标的动画。

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

Layout values are overwritten by layout panes like HBox , AnchorPane , but not by Group or Pane . 布局值会被诸如HBoxAnchorPane类的布局窗格覆盖,但不会被GroupPane覆盖。 Alternatively, set setManaged(false) on the button so the parent container won't interfere with its layout but, you'll have to do all layout by yourself. 或者,在按钮上设置setManaged(false) ,以便父容器不会干扰其布局,但是,您必须自己进行所有布局。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM