如何在类定义中为从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!"));
}
}
代码在动画完成时显示消息但节点本身没有动画。
答案 0 :(得分:0)
尽管您的代码在理论上应该可行,但稍微更好的方法是:
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