javafx未选中复选框时如何停止转换

meg*_*ami 2 checkbox transition javafx

因此,我创建了一个复选框,在选中时将比例过渡应用于矩形。但问题是,即使我取消选中该复选框,转换也会继续进行。关于如何在取消检查后停止它有什么想法吗?

checkbox.setOnAction(e -> {
            ScaleTransition scaleT = new ScaleTransition(Duration.seconds(5), rectangle);
            scaleT.setAutoReverse(true);
            scaleT.setCycleCount(Timeline.INDEFINITE);
            scaleT.setToX(2);
            scaleT.setToY(2);
            scaleT.play();
        });
Run Code Online (Sandbox Code Playgroud)

Sai*_*dem 5

要控制动画,您需要在 CheckBox 侦听器/操作之外定义转换(具有不确定的循环计数)。然后您可以根据需要播放/暂停动画。

下面是快速演示:

在此输入图像描述

import javafx.animation.ScaleTransition;
import javafx.animation.Timeline;
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.CheckBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.scene.shape.Shape;
import javafx.stage.Stage;
import javafx.util.Duration;
public class ScaleTransitionDemo extends Application {
    @Override
    public void start(Stage stage) {
        Shape rectangle = new Rectangle(50, 50, Color.BLUE);
        ScaleTransition transition = new ScaleTransition(Duration.seconds(1), rectangle);
        transition.setDuration(Duration.seconds(1));
        transition.setAutoReverse(true);
        transition.setCycleCount(Timeline.INDEFINITE);
        transition.setToX(3);
        transition.setToY(3);

        CheckBox checkBox = new CheckBox("Animate");
        checkBox.selectedProperty().addListener((obs, old, selected) -> {
            if (selected) {
                transition.play();
            } else {
                transition.pause();
            }
        });

        StackPane pane = new StackPane(rectangle);
        VBox.setVgrow(pane, Priority.ALWAYS);
        VBox root = new VBox(20, checkBox, pane);
        root.setPadding(new Insets(10));
        Scene scene = new Scene(root, 300, 300);
        stage.setScene(scene);
        stage.setTitle("Scale transition");
        stage.show();
    }

    public static void main(String[] args) {
        launch();
    }
}
Run Code Online (Sandbox Code Playgroud)