Skip to content
Advertisement

Sequence animations within a for-loop (JavaFX)

I am writing a program that displays an array of animated circles based on the user’s input for them. The user can determine how fast the animation runs and how many circles there can be displayed on the pane. As of now, the code works perfectly fine. But what I want my code to do is to do the animation one by one (circles all appear at once, but the scaling down animation is happening one by one), I have tried to put the code that runs the animation outside of the for-loop but also didn’t work. I have also put the circle inside of the display code but that also didn’t work. Is there a way to sequence the animations of random shapes in a for loop randomly? I also tried to use the parallel transition on the program but all it did was either no display or give me errors.

This is my code:

private class buttonEvent implements EventHandler<ActionEvent> {
    @Override
    public void handle(ActionEvent e) {
        String countCircles = numOfCircles.getText();
        int circleCount = Integer.parseInt(countCircles);

        String countDuration = duration.getText();
        int speed = Integer.parseInt(countDuration);

        for (int i = 0; i < circleCount; i++) {
            ScaleTransition scaleTr = createTransition(speed);
            display.getChildren().addAll(scaleTr.getNode());
            scaleTr.play();
        }
    }
}

Advertisement

Answer

Maybe this will help you with your problem.


Code

private class buttonEvent implements EventHandler<ActionEvent>
{

    @Override
    public void handle(ActionEvent e)
    {
        String countCircles = numOfCircles.getText();
        int circleCount = Integer.parseInt(countCircles);

        String countDuration = duration.getText();
        int speed = Integer.parseInt(countDuration);
      
        // Edit here: SequentialTransition created
        SequentialTransition sequentialTransition = new SequentialTransition();

        for (int i = 0; i < circleCount; i++)
        {
            ScaleTransition scaleTr = createTransition(speed);
            display.getChildren().addAll(scaleTr.getNode());
            // Edit here: Animation added to sequential transition instead of being played                 
            sequentialTransition.getChildren().add(scaleTr);
        }

        // Edit here: sequential transition being played  
        sequentialTransition.play();
    }
}

I have used SequentialTransition which plays a list of Animations in sequential order. Here is the link to Java Docs for more information: https://docs.oracle.com/javafx/2/api/javafx/animation/SequentialTransition.html

If you find any problems with the solution, please comment.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement