Tag: Animation

  • JavaFX Animation Tutorial with Examples

    JavaFX Animation Tutorial with Examples

    In this article, we will have a deep look at JavaFX Animation. JavaFX provides easy to use animation API (javafx.animation package). There are some predefined animation that can be used out of the box or you can implement custom animations using KeyFrames.

    Following are the main predefined animations in JavaFX.

    TranslateTransition

    Translate transition allows to create movement animation from one point to another within a duration. Using TranslateTransition#setByX / TranslateTransition#setByY, you can set how much it should move in x and y axis respectively. It also possible to set precise destination by using TranslateTransition#setToX / TranslateTransition#setToY.

    import javafx.animation.TranslateTransition;
    import javafx.application.Application;
    import javafx.scene.Group;
    import javafx.scene.Scene;
    import javafx.scene.control.Button;
    import javafx.stage.Stage;
    import javafx.util.Duration;
    
    public class Animation extends Application {
        @Override
        public void start(Stage primaryStage) throws Exception {
            Button btn = new Button("ClickMe");
            Group group = new Group(btn);
            Scene scene = new Scene(group, 600, 600);
    
            //Duration = 2.5 seconds
            Duration duration = Duration.millis(2500);
            //Create new translate transition
            TranslateTransition transition = new TranslateTransition(duration, btn);
            //Move in X axis by +200
            transition.setByX(200);
            //Move in Y axis by +100
            transition.setByY(100);
            //Go back to previous position after 2.5 seconds
            transition.setAutoReverse(true);
            //Repeat animation twice
            transition.setCycleCount(2);
            transition.play();
    
            primaryStage.setScene(scene);
            primaryStage.show();
        }
        public static void main(String[] args) {
            Application.launch(args);
        }
    }
    

    ScaleTransition

    Scale transition is another JavaFX animation which can be used out of the box that allows to animate the scale / zoom of the given object. The object can be enlarged or minimized using this animation.

    import javafx.animation.ScaleTransition;
    import javafx.application.Application;
    import javafx.scene.Group;
    import javafx.scene.Scene;
    import javafx.scene.control.Button;
    import javafx.stage.Stage;
    import javafx.util.Duration;
    
    public class Animation extends Application {
    
      @Override
      public void start(Stage primaryStage) throws Exception {
        Button btn = new Button("Genuine Coder");
        Group group = new Group(btn);
        Scene scene = new Scene(group, 600, 600);
    
        //Duration = 2.5 seconds
        Duration duration = Duration.millis(2500);
        //Create new scale transition
        ScaleTransition scaleTransition = new ScaleTransition(duration, btn);
        //Set how much X should enlarge
        scaleTransition.setByX(1.5);
        //Set how much Y should
        scaleTransition.setByY(1.5);
        scaleTransition.play();
    
        primaryStage.setScene(scene);
        primaryStage.show();
      }
    
      public static void main(String[] args) {
        Application.launch(args);
      }
    }
    

    RotateTransition

    Rotate transition provides animation for rotating an object. We can provide upto what angle the node should rotate by toAngle. Using byAngle we can specify how much it should rotate from current angle of rotation.

    import javafx.animation.RotateTransition;
    import javafx.application.Application;
    import javafx.scene.Group;
    import javafx.scene.Scene;
    import javafx.scene.control.Button;
    import javafx.stage.Stage;
    import javafx.util.Duration;
    
    public class Animation extends Application {
    
      @Override
      public void start(Stage primaryStage) {
        Button btn = new Button("Genuine Coder");
        Group group = new Group(btn);
        Scene scene = new Scene(group, 600, 600);
    
        //Duration = 2.5 seconds
        Duration duration = Duration.millis(2500);
        //Create new rotate transition
        RotateTransition rotateTransition = new RotateTransition(duration, btn);
        //Rotate by 200 degree
        rotateTransition.setByAngle(200);
        rotateTransition.play();
    
        primaryStage.setScene(scene);
        primaryStage.show();
      }
    
      public static void main(String[] args) {
        Application.launch(args);
      }
    }
    

    FadeTransition

    Fade transition creates a fade in / fade out effect by controlling opacity of the object. We can make fade in transition or fade out transition in JavaFX by setting the to and from value.

    //Fade in transition
    FadeTransition fadeInTransition = new FadeTransition(Duration.millis(1500), btn);
    fadeInTransition.setFromValue(0.0);
    fadeInTransition.setToValue(1.0);
    
    //Fade out transition
    FadeTransition fadeOutTransition = new FadeTransition(Duration.millis(1500), btn);
    fadeOutTransition.setFromValue(1.0);
    fadeOutTransition.setToValue(0.0);
    

    PathTransition

    Path transition provides option to move object through a specified path. The path can be anything from simple straight line to complex quadratic curves. Following code rotates button through a circular path locate at (200,200) with radius 50

    import javafx.animation.PathTransition;
    import javafx.application.Application;
    import javafx.scene.Group;
    import javafx.scene.Scene;
    import javafx.scene.control.Button;
    import javafx.scene.shape.Circle;
    import javafx.stage.Stage;
    import javafx.util.Duration;
    
    public class Animation extends Application {
    
      @Override
      public void start(Stage primaryStage) {
        Button btn = new Button("Genuine Coder");
        Group group = new Group(btn);
        Scene scene = new Scene(group, 600, 600);
    
        //Create new path transition
        PathTransition pathTransition = new PathTransition();
        pathTransition.setDuration(Duration.millis(2500));
        //Set node to be animated
        pathTransition.setNode(btn);
        //Rotate button through a circular path locate at (200,200) with radius 50
        pathTransition.setPath(new Circle(200, 200, 50));
    
        pathTransition.play();
    
        primaryStage.setScene(scene);
        primaryStage.show();
      }
    
      public static void main(String[] args) {
        Application.launch(args);
      }
    }
    

    Combine Animation Sequentially with SequentialTransition

    Sequential transition allows to combine two or more transition we have discussed so far. After the completion of one transition, the next will be started. The following code will apply rotate transition and scale transition sequentially.

    //Create rotate transition
    RotateTransition rotateTransition = new RotateTransition(Duration.seconds(1));
    rotateTransition.setByAngle(180f);
    //Create scale transition
    ScaleTransition scaleTransition = new ScaleTransition(Duration.seconds(1));
    scaleTransition.setByX(1.5f);
    
    //First do rotateTransition, then do scaleTransition
    SequentialTransition sequentialTransition = new SequentialTransition(rotateTransition, scaleTransition);
    sequentialTransition.play();
    

    Combine Animation Parallely with ParallelTransition

    Parallel transition is very much similar to sequential transition. Except, it works on parallel. All the animations applied will be played in parallel. We can specify two or more transition to execute in parallel.

    //Create rotate transition
    RotateTransition rotateTransition = new RotateTransition(Duration.seconds(1));
    rotateTransition.setByAngle(180f);
    //Create scale transition
    ScaleTransition scaleTransition = new ScaleTransition(Duration.seconds(1));
    scaleTransition.setByX(1.5f);
    
    //Play both rotateTransition as well as scaleTransition in prallel
    ParallelTransition sequentialTransition = new ParallelTransition(rotateTransition, scaleTransition);
    sequentialTransition.play();
    

    KeyFrame Animation

    KeyFrame animation is one of the most key features of JavaFX Animation. The API javafx.animation.KeyFrame can be used to animate any JavaFX property. For example, let’s say you want to animate width of your application window. You can use widthProperty with KeyFrame to animate the width of your application window.

    Watch video on using KeyFrame animation to create slide-in effect in JavaFX.

    The following example loads a scene with slide in effect using JavaFX KeyFrame API

    Parent root = getNextSceneRoot();
    parentContainer.getChildren().add(root);
    
    //Create a timeline instance
    Timeline timeline = new Timeline();
    //Create a keyValue. We need to slide in -- We gradually decrement Y value to Zero
    KeyValue kv = new KeyValue(root.translateYProperty(), 0, Interpolator.EASE_IN);
    //Create keyframe of 1s with keyvalue kv
    KeyFrame kf = new KeyFrame(Duration.seconds(1), kv);
    //Add frame to timeline
    timeline.getKeyFrames().add(kf);
    
    //Start animation
    timeline.play();
    

     

    In this chapter we familiarized with JavaFX animation API. JavaFX provides a good set of predefined animation set and a powerful KeyFrame animation API.

    You Might also be interested in:-

     

  • JavaFX Scene Switch Animation

    JavaFX Scene Switch Animation

    We all love JavaFX for its modern look and easy to use user interface APIs. In this article we will discuss about JavaFX Scene Switch (Change) animation. I have implemented two types of scene change animation. Fading Scenes and Sliding Scenes.

    By default, JavaFX animation api does not provide a direct option animate a scene change. But we can use the following way.

    1. Load primary stage with a scene. Enclose this scene in a root container. This container can be of your preference. StackPane, Group etc can be used.
    2. When changing scenes, remove everything from this root container.
    3. Load the scene to be loaded to a variable. Add it new scene to the root container with animation.

    Sliding Scene Transition

    In this animation, we will get a nice sliding effect for the scenes. You can see the preview in the following GIF.

    JavaFX Scene Sliding Animation
    JavaFX Scene Sliding Animation

    The idea here is to load the new scene beyond the visibility of the screen. For example, if the window height is 500px, then load the new scene at 500px. Then using KeyFrame animation, take the scene translateY to 0. This creates a slide in effect from bottom. Using translateX, we can implement slide in effect from sides.

    Let’s see this in code. Following file is the first scene’s controller. When loadSecondScene() is called, second scene will be added.

    /**
     * Removed Imports for code simplicity
     * FILE - Scene 1 Controller. On button Click, Scene 2 will be loaded  
     * @author Genuine Coder
     */
    public class FirstSceneController implements Initializable {
        @FXML
        private AnchorPane anchorRoot;
        @FXML
        private StackPane parentContainer;
    
        @FXML
        private void loadSecondScene(ActionEvent event) throws IOException {
            Parent root = FXMLLoader.load(getClass().getResource("myscene2.fxml"));
            Scene scene = anchorRoot.getScene();
            //Set Y of second scene to Height of window
            root.translateYProperty().set(scene.getHeight());
            //Add second scene. Now both first and second scene is present
            parentContainer.getChildren().add(root);
    
            //Create new TimeLine animation
            Timeline timeline = new Timeline();
            //Animate Y property
            KeyValue kv = new KeyValue(root.translateYProperty(), 0, Interpolator.EASE_IN);
            KeyFrame kf = new KeyFrame(Duration.seconds(1), kv);
            timeline.getKeyFrames().add(kf);
            //After completing animation, remove first scene
            timeline.setOnFinished(t -> {
                parentContainer.getChildren().remove(anchorRoot);
            });
            timeline.play();
        }
    }
    

    Watch the Slide Transition in action from Genuine Coder Channel

    Fading Scene Transition

    Fading screen transition can also be implemented with a similar concept as of Sliding Screen transition.  The idea is, we apply a fade out transition for the first scene. After completion of fade out transition of first scene, we add second scene. The second scene will be added with zero opacity. Then using fade in transition we make the second scene visible.

    You can see the program in action in the following Genuine Coder Tutorial video.