# Animation of adding / removing nodes from VBox

Method hide_old_show_new (I can't think of a suitable name) gradually, using FadeTransition, removes all nodes (from last to first) and then adds new nodes (from first to last)

But, it is unnecessarily complex.

Do you know how to simplify it? Or a better algorithm? I'll be grateful for the improvement.

However, I do not want to use an algorithm using *.fxml.

import java.util.ArrayList;
import javafx.scene.text.Text;
import javafx.util.Duration;

public final class Cart extends javafx.scene.layout.VBox {

public Cart(double x, double y, double width, double height) {
super();
setLayoutX(x);
setLayoutY(y);
setWidth(width);
setHeight(height);
}

var size = getChildren().size();
if (size > 0 && !getChildren().get(0).equals(nodes.get(0))) {
transition = new FadeTransition(Duration.millis(200), getChildren().get(size - 1));
transition.setFromValue(1);
transition.setToValue(0);
transition.setOnFinished((event) -> {
getChildren().remove(size - 1);
hide_old_show_new(nodes);
});
transition.play();
} else if (size < nodes.size()) {
getChildren().get(size).setOpacity(0);
transition.setFromValue(0);
transition.setToValue(1);
transition.setOnFinished((event) -> {
hide_old_show_new(nodes);
});
transition.play();
}
return transition;
}
}

• The question would be better if the entire class was included, right now there really isn't enough to review. – pacmaninbw Jun 28 at 13:10
• OK. I've given the whole class. Of course, it is not yet complete. – Michal Rama Jun 28 at 14:50

So I divided it into two methods. This made the conditions considerably easier.

Still, it doesn't seem perfect to me. Plus, I found a mistake. If I run a new animation, an error occurs if the old animation has not been completed yet.

But I don't know how to treat it.

Do you have any idea how, please?

Thank you

public FadeTransition hide_old(ArrayList<Text> nodes) {
var size = getChildren().size();
if (size > 0) {
transition = new FadeTransition(Duration.millis(200), getChildren().get(size - 1));
transition.setFromValue(1);
transition.setToValue(0);
transition.setOnFinished((event) -> {
getChildren().remove(size - 1);
hide_old(nodes);
});
transition.play();
} else {
show_new(nodes);
}
return transition;
}

private void show_new(ArrayList<Text> nodes) {
var size = getChildren().size();
if (size < nodes.size()) {