Monday, February 6, 2012

JavaFX 2 Animation: Path Transitions

One of the flashiest aspects of JavaFX 2 is its animation support. The insightful Creating Transitions and Timeline Animation in JavaFX covers using both Transitions and Timelines in JavaFX 2. In this blog post, I adapt an example provided in that tutorial to specifically demonstrate Path Transitions.

Example 2 ("Path Transition") shown in Creating Transitions and Timeline Animation in JavaFX demonstrates creating a Path with classes from the JavaFX 2 "shapes" package: javafx.scene.shape.Path, javafx.scene.shape.MoveTo, and javafx.scene.shape.CubicCurve. That example then demonstrates instantiation of a javafx.animation.PathTransition and applying an instantiated javafx.scene.shape.Rectangle to move along the created Path.

In my code listing below, I've made some slight changes to Example 2 in Creating Transitions and Timeline Animation in JavaFX. I have specifically changed the moving shape from a rectangle to a Circle, added two "end knobs" to the path as two separate circles, and added the ability to change the opacity of the path along with the animated circle moves. The nice side effect of using a zero opacity is that the path itself does not appear and it instead looks like the circle is moving along freely. I tried to break each major piece of this up into its own private method to make it easier to see the "chunks" of functionality.

JavaFxAnimations.java
package dustin.examples;

import java.util.List;
import javafx.animation.PathTransition;
import javafx.animation.Timeline;
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.paint.Color;
import javafx.scene.shape.*;
import javafx.stage.Stage;
import javafx.util.Duration;

/**
 * Simple example demonstrating JavaFX animations.
 * 
 * Slightly adapted from Example 2 ("Path Transition") which is provided in
 * "Creating Transitions and Timeline Animation in JavaFX"
 * (http://docs.oracle.com/javafx/2.0/animations/jfxpub-animations.htm).
 * 
 * @author Dustin
 */
public class JavaFxAnimations extends Application
{
   /**
    * Generate Path upon which animation will occur.
    * 
    * @param pathOpacity The opacity of the path representation.
    * @return Generated path.
    */
   private Path generateCurvyPath(final double pathOpacity)
   {
      final Path path = new Path();
      path.getElements().add(new MoveTo(20,20));
      path.getElements().add(new CubicCurveTo(380, 0, 380, 120, 200, 120));
      path.getElements().add(new CubicCurveTo(0, 120, 0, 240, 380, 240));
      path.setOpacity(pathOpacity);
      return path;
   }

   /**
    * Generate the path transition.
    * 
    * @param shape Shape to travel along path.
    * @param path Path to be traveled upon.
    * @return PathTransition.
    */
   private PathTransition generatePathTransition(final Shape shape, final Path path)
   {
      final PathTransition pathTransition = new PathTransition();
      pathTransition.setDuration(Duration.seconds(8.0));
      pathTransition.setDelay(Duration.seconds(2.0));
      pathTransition.setPath(path);
      pathTransition.setNode(shape);
      pathTransition.setOrientation(PathTransition.OrientationType.ORTHOGONAL_TO_TANGENT);
      pathTransition.setCycleCount(Timeline.INDEFINITE);
      pathTransition.setAutoReverse(true);
      return pathTransition;
   }

   /**
    * Determine the path's opacity based on command-line argument if supplied
    * or zero by default if no numeric value provided.
    * 
    * @return Opacity to use for path.
    */
   private double determinePathOpacity()
   {
      final Parameters params = getParameters();
      final List<String> parameters = params.getRaw();
      double pathOpacity = 0.0;
      if (!parameters.isEmpty())
      {
         try
         {
            pathOpacity = Double.valueOf(parameters.get(0));
         }
         catch (NumberFormatException nfe)
         {
            pathOpacity = 0.0;
         }
      }
      return pathOpacity;
   }

   /**
    * Apply animation, the subject of this class.
    * 
    * @param group Group to which animation is applied.
    */
   private void applyAnimation(final Group group)
   {
      final Circle circle = new Circle(20, 20, 15);
      circle.setFill(Color.DARKRED);
      final Path path = generateCurvyPath(determinePathOpacity());
      group.getChildren().add(path);
      group.getChildren().add(circle);
      group.getChildren().add(new Circle(20, 20, 5));
      group.getChildren().add(new Circle(380, 240, 5));
      final PathTransition transition = generatePathTransition(circle, path);
      transition.play(); 
   }

   /**
    * Start the JavaFX application
    * 
    * @param stage Primary stage.
    * @throws Exception Exception thrown during application.
    */
   @Override
   public void start(final Stage stage) throws Exception
   {
      final Group rootGroup = new Group();
      final Scene scene = new Scene(rootGroup, 600, 400, Color.GHOSTWHITE);
      stage.setScene(scene);
      stage.setTitle("JavaFX 2 Animations");
      stage.show();
      applyAnimation(rootGroup);
   }

   /**
    * Main function for running JavaFX application.
    * 
    * @param arguments Command-line arguments; optional first argument is the
    *    opacity of the path to be displayed (0 effectively renders path
    *    invisible).
    */
   public static void main(final String[] arguments)
   {
      Application.launch(arguments);
   }
}

The following series of screen snapshots show this simple JavaFX animation example in action. They are listed in order of descending opacity (from 1.0 to 0.0).

Demonstration of Adapted PathTransition Example (Opacity 1.0)
Demonstration of Adapted PathTransition Example (Opacity 0.2)
Demonstration of Adapted PathTransition Example (Opacity 0.05)
Demonstration of Adapted PathTransition Example (Opacity 0.0)

Each of the above screen snapshots was taken after running the application with the specified command-line argument (1, 0.2, 0.05, and 0).

This adapted example has demonstrated using PathTransition to animate a node's movement along the prescribed path (I have blogged on use of Path and some of its alternatives before). Developers can implement their own derivative of Transition and there are other supplied transitions supported as well (such as FadeTransition, ParallelTransition, and SequentialTransition).

It is a straightforward process to quickly begin applying JavaFX 2 animation using the provided Transition classes.

No comments: