简体   繁体   中英

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.

If you want to move the Button , you should choose a different layout as parent or use the translateX property instead. translateX moves the Button relative to the position where the parent layout places it ( 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 . 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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