Montag, 30. Juni 2014

Custom Transitions

Long time since my last post, but I didn't had enough time to do more JavaFx work...

JavaFX has a lot of built in ready to use animations, called Transitions. There is a base class javafx.animation.Transition and many useful implementations, like the ScaleTransition for animating the size, the RotateTransition for animationg the rotation, or the FadeTransition for animation the transparency or the TranslateTransition for moving a node.

They are easy to use: Instantiate them, set a start and end value and a duration, and call play. Here an example that fades out myNode in 500 milliseconds:

FadeTransition transition = new FadeTransition(Duration.millis(500), myNode);
transition.setFromValue(1);
transition.setToValue(0);
transition.play();

But sometimes, the built in transitions don't fit. Either because the built in transitions only work on nodes, but e.g. not on popups, or because you want to have an animation, that is not yet implemented. So write your own! It is very easy. Just subclass the abstract class Transition and implement the protected method interpolate. Thats all. The param frac is a double between 0 and 1. From this value, the value change of your transition has to be calculated. This is very easy if the target value is a double between 0 and 1 like for opacity. So the easiest possible example is a fade transition for popups:

private class FadeTransitionForPopup extends Transition{
  private Popup popup;

  public FadeTransitionForPopup (Popup popup){
    this.popup = popup;
  } 


  @Override
  protected void interpolate(double frac) {

    popup.setOpacity(frac)    
  }
}


Keine Kommentare:

Kommentar veröffentlichen

Kommentar veröffentlichen