Animation JavaFx:如何设置继承节点的动画?

Animation JavaFx:如何设置继承节点的动画?,animation,javafx,transition,Animation,Javafx,Transition,如何在类定义中设置从ImageView继承的类对象的动画 我的代码: public class CustomImageView extends ImageView{ public CustomImageView(String imageLocation){ this.setImage(new Image(imageLocation)); FadeTransition fadeIn = new FadeTransition(); fadeIn.setDuration(n

如何在类定义中设置从ImageView继承的类对象的动画

我的代码:

public class CustomImageView extends ImageView{

public CustomImageView(String imageLocation){

    this.setImage(new Image(imageLocation));
    FadeTransition fadeIn = new FadeTransition();
    fadeIn.setDuration(new Duration(2000));
    fadeIn.setFromValue(0);
    fadeIn.setToValue(1);
    fadeIn.setNode(this);
    fadeIn.play();

    fadeIn.setOnFinished(ae->System.out.println("Finished!"));
    }
}

当动画完成但节点本身未设置动画时,代码将显示消息。

虽然您的代码理论上应该可以工作,但更好的方法是:

public class CustomImageView extends ImageView {
    public CustomImageView(String imageLocation){
        this.setImage(new Image(imageLocation));
        this.setOpacity(0); // completely transparent when created
    }

    // can play anytime on demand
    public void playFadeInAnimation(Runnable action) {
        FadeTransition fadeIn = new FadeTransition(Duration.seconds(2), this);
        fadeIn.setFromValue(0);
        fadeIn.setToValue(1);
        fadeIn.setOnFinished(e -> action.run());
        fadeIn.play();
    }
}
您正在使用CustomImageView的其他地方

CustomImageView view = new CustomImageView(...);
someParent.getChildren().add(view); // display on screen
view.playFadeInAnimation(...);      // play animation