在 javafx 中一次将转换应用于一组中的一个节点

applying a transition to one node at time in a group in javafx

我试图在 javafx 中一次淡入一个对象。我尝试使用 for 循环遍历一组节点,但一组中的所有节点似乎同时显示,而不是一次淡入一个节点。我似乎无法弄清楚问题出在哪里。

    Group points = new Group();

        for(int i = 0; i < ipSize; i++){
            double xCentre = ipXPoints[i]-5;
            double yCentre = ipYPoints[i]-5;

            Circle point = new Circle(xCentre , yCentre, 10, Color.FORESTGREEN);
            points.getChildren().add(point);
        }
pane.getChildren().add(points);

Timeline timeline = new Timeline();
        for(Node node: pane.getChildren()){
            timeline.getKeyFrames().addAll(
                    new KeyFrame(Duration.seconds(0), // set start position at 0
                        new KeyValue(node.opacityProperty(), 0, Interpolator.EASE_BOTH)
                    ),
                    new KeyFrame(Duration.seconds(3), 
                        new KeyValue(node.opacityProperty(), 1, Interpolator.EASE_BOTH)
                    )
                );
timeline.play();
}

编辑: 我也试过这个,但它会同时播放所有节点,而不是一次播放一个。

FadeTransition fade = new FadeTransition(Duration.seconds(3), node);
            fade.setFromValue(0);
            fade.setToValue(1);
            fade.setAutoReverse(false);
            fade.setCycleCount(1);
            fade.setInterpolator(Interpolator.EASE_BOTH);
            fade.play();

感谢您的帮助:)

所有圆圈同时显示的原因是KeyFrame持续时间实际上不是帧的持续时间,而是从动画开始的绝对持续时间。因此,您指定所有转换都发生在 0 到 3 之间。要修复您的代码,您需要将第一对关键帧持续时间设置为 0s 和 3s,第二对设置为 3s 和 6s,第三对设置为 6s 和 9s,依此类推。

或者,您可以使用 SequentialTransition of FadeTransitions:

import java.util.Random;

import javafx.animation.FadeTransition;
import javafx.animation.SequentialTransition;
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.stage.Stage;
import javafx.util.Duration;


public class SequentialFadeIn extends Application {

    @Override
    public void start(Stage stage) {
        int width = 600;
        int height = 400;

        Group points = new Group();
        SequentialTransition seq = new SequentialTransition();
        Random random = new Random();
        for(int i = 0; i < 10; i++){
            double xCentre = random.nextInt(width);
            double yCentre = random.nextInt(height);

            Circle point = new Circle(xCentre , yCentre, 10, Color.FORESTGREEN);
            point.setOpacity(0.0);

            points.getChildren().add(point);
            FadeTransition fade = new FadeTransition(Duration.seconds(3), point);
            fade.setToValue(1.0);
            seq.getChildren().add(fade);
        }

        stage.setScene(new Scene(points, width, height));
        stage.show();
        seq.play();
    }

    public static void main(String[] args) {
        launch(args);
    }
}