Adding Node's animated to a VBox

2019-03-04 23:29发布

问题:

I am looking for a solution to add node's with fade-in or flipping or any animation. Thanks for any help.

I found the same question but without any further help here: Animated component adding-delete in a VBox

回答1:

As jewelsea already mentioned, you would use Transitions. Here is an example of how to do it for your use case :

public static void addFadingIn(final Node node, final Group parent) {
    final FadeTransition transition = new FadeTransition(Duration.millis(250), node);
    transition.setFromValue(0);
    transition.setToValue(1);
    transition.setInterpolator(Interpolator.EASE_IN);
    parent.getChildren().add(node);
    transition.play();
  }

  public static void removeFadingOut(final Node node, final Group parent) {
    if (parent.getChildren().contains(node)) {
      final FadeTransition transition = new FadeTransition(Duration.millis(250), node);
      transition.setFromValue(node.getOpacity());
      transition.setToValue(0);
      transition.setInterpolator(Interpolator.EASE_BOTH);
      transition.setOnFinished(finishHim -> {
        parent.getChildren().remove(node);
      });
      transition.play();
    }
  }

Or a more gerneral implementation using Java8 :

 public static void addAnimating(final Node node, final Group parent,
      final Supplier<Animation> animationCreator) {
    parent.getChildren().add(node);
    animationCreator.get().play();
  }

  public static void removeAnimating(final Node node, final Group parent,
      final Supplier<Animation> animationCreator) {
    if (parent.getChildren().contains(node)) {
      final Animation animation = animationCreator.get();
      animation.setOnFinished(finishHim -> {
        parent.getChildren().remove(node);
      });
      animation.play();

    }
  }

You can find a full example on https://gist.github.com/bugabinga/9576634



回答2:

You can use the built-in Transitions or a 3rd party library such as FXExperience Canned Animations.

For an example of integrating an animation with a standard layout pane see this LayoutAnimator code used in the example solution to: Animation upon layout changes. The LayoutAnimator is very generic and will work with other Panes than the FlowPane sample it is provided with (it just looks a bit cooler with the FlowPane).