2015-10-31 23 views
0

如何從類定義中爲從ImageView繼承的類創建對象?JavaFx:如何動畫一個被繼承的節點?

我的代碼:

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

雖然你的代碼應該理論上的工作,一個稍微好一點的做法是:

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