Animation
One of the exciting features provided by Project Scene Graph is a powerful animation framework. You can use this framework to add a dynamic quality to your user interfaces. Before you play with the animation framework, I recommend that you familiarize yourself with the following articles and blog entries written by former Sun employee and animation framework developer Chet Haase:
- Timing is Everything: As far as I can tell, the animation framework began as a simple timing framework that Chet introduced via this article in early 2005.
- Time Again: Chet's earlier article introduced timing basics, and this article builds on that foundation by introducing a more powerful timing framework.
- Been There, Scene That, Part 1: In early 2008, Chet introduced a two-part blog that focused on the evolution of the timing framework into the animation framework used by Project Scene Graph.
- Been There, Scene That, Part 2: The second part of Chet's two-part blog on the evolution of the timing framework introduces you to the Timeline and MotionPath classes.
Instead of revisiting Chet's excellent coverage of the animation framework, I'll assume that you've read this material. Instead, I want to gently introduce you to this framework in terms of the previous demo, and two demos that I present later in this section. Let's begin by focusing on Listing 1's use of the framework's com.sun.scenario.animation.Clip class to animate an SGComposite node's opacity.
The Clip class introduces a single animation. Although multiple animation clips can be strung together to create a complex animation, I decided to keep Listing 1 simple by focusing on a single clip. If you refer to Listing 1, you'll discover that I created the Clip instance by invoking the following factory method, which makes it possible to animate an object's property:
public static <T> Clip create(long duration, float repeatCount, Object target, String property, T... keyValues)
This method has the following parameters:
- duration: Specify the length (in milliseconds) of an animation cycle. Pass Clip.INDEFINITE to have the animation run forever.
- repeatCount: Specify the number of times to repeat the animation—each cycle runs in the opposite direction (such as opaque to transparent on one cycle, and transparent to opaque on the next cycle). Pass Clip.INDEFINITE to rerun the animation forever—obviously, you wouldn't also pass Clip.INDEFINITE to duration. An IllegalArgumentException is thrown if you pass a negative value to repeatCount.
- target: Specify the object whose property is to be animated.
- property: Specify the target object's property to animate. Although you can change the case of the property name's first letter (as in "opacity"), an IllegalArgumentException is thrown if the property doesn't exist ("OPacity" or "Opaxity", for example).
- keyValues: Specify a set of values that the property takes on at appropriate times during the animation.
In Listing 1, I specified a duration of 1500 milliseconds, an INDEFINITE repeat count, compNode as the object whose "Opacity" property is to be animated, and 1.0f and 0.0f as the values that the property takes on at the start and end of the animation. Because each animation cycle runs in reverse to the previous cycle, the opacity may start at either of these values, and end at the opposite value.
Regarding properties, the animation framework uses reflection to look for the appropriate property setter method in the target object. For example, when compNode and "Opacity" are passed to create(), the framework looks for SGComposite's public void setOpacity(float opacity) method in compNode.
After creating a Clip, you can start the animation by invoking Clip's public void start() method. Animations that run indefinitely can be stopped by invoking Clip's public void stop() method. For example, you could register a mouse listener with Listing 1's sceneNode object, overriding the mouseClicked() method to invoke stop() whenever the mouse is clicked anywhere on the scene.
Rotating a Swing Button
I’ve prepared a second animation demo that rotates a Swing button around its center in response to the button being clicked. Although this example won't teach you much more about the animation framework, you will learn how to wrap an SGComponent node around a Swing component, how to work with SGMouseListener, and more. Listing 2 presents this demo's source code.
Listing 2 RotatingButton.java
// RotatingButton.java import java.awt.*; import java.awt.event.*; import java.awt.geom.*; import java.util.*; import javax.swing.*; import com.sun.scenario.animation.*; import com.sun.scenario.scenegraph.*; import com.sun.scenario.scenegraph.event.*; public class RotatingButton { final static int WIDTH = 200; final static int HEIGHT = 150; public static void main (String [] args) { Runnable r = new Runnable () { public void run () { createAndShowGUI (); } }; EventQueue.invokeLater (r); } public static void createAndShowGUI () { JFrame f = new JFrame ("Rotating Button"); f.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE); // JSGPanel is a JComponent that renders a scene graph. Instead of // instantiating this class, this method instantiates a subclass that // allows a scene graph to be properly centered. CenteringSGPanel panel = new CenteringSGPanel (); panel.setBackground (Color.BLACK); panel.setPreferredSize (new Dimension (WIDTH, HEIGHT)); // Create a Swing button component that outputs a message to the // standard output in response to being clicked. JButton btn = new JButton ("Click Me!"); btn.addActionListener (new ActionListener () { public void actionPerformed (ActionEvent ae) { System.out.println ("button clicked"); } }); // Insert the Swing button component into the scene graph via an // SGComponent node. SGComponent compNode = new SGComponent (); compNode.setID ("compNode: SGComponent"); compNode.setComponent (btn); // Register a mouse listener with this node that, in response to a mouse // click on the node, rotates the node and its button 360 degrees in a // clockwise direction. SGMouseListener listener; listener = new SGMouseListener () { public void mouseClicked (MouseEvent me, SGNode node) { System.out.println ("Receiving mouse event from "+ node.getID ()); // Create an animation clip for animating the button. // Each cycle will last for .5 seconds, the animation // will consist of 1 cycle, the animation will // repeatedly invoke the SGTransform.Rotate timing // target (which happens to be the grandparent of the // node argument passed to mouseClicked()), the // property being animated is Rotation, and this // property is animated from 0.0 radians to 2*Math.PI // radians (a full circle). The positive value // specifies a clockwise rotation. Clip spinner = Clip.create (500, 1, node.getParent () .getParent (), "Rotation", 0.0, 2*Math.PI); // Start the animation. spinner.start (); } public void mouseDragged (MouseEvent me, SGNode node) { } public void mouseEntered (MouseEvent me, SGNode node) { } public void mouseExited (MouseEvent me, SGNode node) { } public void mouseMoved (MouseEvent me, SGNode node) { } public void mousePressed (MouseEvent me, SGNode node) { } public void mouseReleased (MouseEvent me, SGNode node) { } public void mouseWheelMoved (MouseWheelEvent me, SGNode node) { } }; compNode.addMouseListener (listener); // The scene consists of a single SGComponent node that houses a Swing // JButton component. To rotate the node around a point, we need to // create a chain of three transforms. The first transform translates // the node's rotation point (which is the node's center point in this // application) to the node's origin, the second transform performs the // rotation, and the third transform translates the node's rotation // point back to its original location. This transform chain is created // within the createRotationNode() method. SGTransform scene = createRotationNode (compNode); // Establish the scene. panel.setScene (scene); // Dump the scene graph hierarchy to the standard output. dump (panel.getScene (), 0); // Install the panel into the Swing hierarchy, pack it to its preferred // size, and don't let it be resized. Furthermore, center and display // the main window on the screen. f.setContentPane (panel); f.pack (); f.setResizable (false); f.setLocationRelativeTo (null); f.setVisible (true); } // The following createRotationNode() method is based on a nearly identical // createRotation() method in Hans Muller's "Introducing the SceneGraph // Project" blog entry: // http://weblogs.java.net/blog/hansmuller/archive/2008/01/introducing_the.html static SGTransform createRotationNode (SGNode node) { Rectangle2D nodeBounds = node.getBounds (); double cx = nodeBounds.getCenterX (); double cy = nodeBounds.getCenterY (); SGTransform toOriginT = SGTransform.createTranslation (-cx, -cy, node); toOriginT.setID ("toOriginT: SGTransform.Translate"); SGTransform.Rotate rotateT = SGTransform.createRotation (0.0, toOriginT); rotateT.setID ("rotateT: SGTransform.Rotate"); SGTransform toNodeT = SGTransform.createTranslation (cx, cy, rotateT); toNodeT.setID ("toNodeT: SGTransform.Translate"); return toNodeT; } public static void dump (SGNode node, int level) { for (int i = 0; i < level; i++) System.out.print (" "); System.out.println (node.getID ()); if (node instanceof SGParent) { java.util.List<SGNode> children = ((SGParent) node).getChildren (); Iterator<SGNode> it = children.iterator (); while (it.hasNext ()) dump (it.next (), level+1); } } } // JSGPanel has been subclassed in order to properly center the scene within // this Swing component. class CenteringSGPanel extends JSGPanel { private SGNode sceneNode; private SGTransform.Translate centeringTNode; @Override public void doLayout () { if (sceneNode != null) { Rectangle2D bounds = sceneNode.getBounds (); centeringTNode.setTranslateX (-bounds.getX ()+ (getWidth ()-bounds.getWidth ())/2.0); centeringTNode.setTranslateY (-bounds.getY ()+ (getHeight ()-bounds.getHeight ())/2.0); } } @Override public void setScene (SGNode sceneNode) { this.sceneNode = sceneNode; centeringTNode = SGTransform.createTranslation (0f, 0f, sceneNode); centeringTNode.setID ("centeringTNode: SGTransform.Translate"); super.setScene (centeringTNode); } }
To rotate a JButton or another Swing component, an SGComponent node must be wrapped around the Swing component, and then this node rotated. Listing 2 accomplishes the former task by invoking the SGComponent public void setComponent(java.awt.Component component) method. (You can retrieve this component by calling the companion public final Component getComponent() method.)
After storing the JButton instance in the SGComponent node, Listing 2 creates an anonymous inner class that implements SGMouseListener—I could have extended SGMouseAdapter and avoided having to code empty listener methods. It then registers this listener with the SGComponent node so that it can rotate the node in response to a mouse button click, whenever the mouse is positioned over the node.
Rotation takes place within the SGMouseListener mouseClicked() method by having this method's event-handling code create and start an animation Clip in a similar fashion to Listing 1. This code ignores the method's first parameter, a MouseEvent that describes the event. However, it uses the second parameter, an SGNode, to access an SGTransform.Rotate node.
This node is created in Listing 2's createRotationNode() method as part of a transformation sequence that makes it possible to rotate the SGComponent node around its (and the JButton's) center point: translate-center-point-to-node-origin transform, followed by a rotate transform, followed by a translate-center-point-from-node-origin transform. This final transform is returned.
The node.getParent ().getParent () expression first invokes getParent() on the node argument (which is the SGComponent instance) to retrieve the translate-center-point-to-node-origin transform instance, and then invokes getParent() on this instance to obtain the SGTransform.Rotate instance.
Reflection, node.getParent ().getParent (), and the "Rotation" argument passed to Clip's create() method help the animation framework find SGTransform.Rotate's setRotation() method. Furthermore, the 0.0 and 2*Math.PI arguments are passed as doubles instead of floats because reflection requires the method's actual argument type: double for setRotation().
After compiling RotatingButton.java and running the resulting application in the same manner as the previous HelloPSG application, you'll see a window similar to that shown in Figure 2.
Figure 2 Click the button to rotate it clockwise in a single 360-degree circle.
You'll also discover, in the standard output, the following hierarchy of nodes that set up a translation to center the scene, set up a translate/rotate/translate sequence to rotate the button's node around its center, and render the button's node (including the button):
centeringTNode: SGTransform.Translate toNodeT: SGTransform.Translate rotateT: SGTransform.Rotate toOriginT: SGTransform.Translate compNode: SGComponent
Scaling Images
The final animation demo, ScaledImages, presents three side-by-side images. Moving the mouse pointer over an image causes the image to shrink to a smaller size or to expand back to its original size. In addition to new animation features, this demo introduces you to the SGImage class for storing java.awt.Images in a scene graph. Check out Listing 3 for the source code.
Listing 3 ScaledImages.java
// ScaledImages.java import java.awt.*; import java.awt.event.*; import java.awt.geom.*; import java.awt.image.*; import java.io.*; import java.util.*; import javax.imageio.*; import javax.swing.*; import com.sun.scenario.animation.*; import com.sun.scenario.scenegraph.*; import com.sun.scenario.scenegraph.event.*; public class ScaledImages { final static int WIDTH = 750; final static int HEIGHT = 400; final static int SCALE_TIME = 100; final static double SCALE_DOWN_LIMIT = 0.25; public static void main (String [] args) { Runnable r = new Runnable () { public void run () { createAndShowGUI (); } }; EventQueue.invokeLater (r); } public static void createAndShowGUI () { JFrame f = new JFrame ("Scaled Images"); f.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE); // JSGPanel is a JComponent that renders a scene graph. Instead of // instantiating this class, this method instantiates a subclass that // allows a scene graph to be properly centered. CenteringSGPanel panel = new CenteringSGPanel (); panel.setBackground (Color.BLACK); panel.setPreferredSize (new Dimension (WIDTH, HEIGHT)); // Create a group to hold three SGImage nodes that each present a single // image. SGGroup imageNodes = new SGGroup (); imageNodes.setID ("imageNodes: SGGroup"); // I've chosen to present images of three planets: Venus, Mars, and // Jupiter. String [] imageNames = { "venus.gif", "mars.gif", "jupiter.gif" }; // Populate the group. int xOffset = 0; for (String name: imageNames) { SGImage imageNode = new SGImage (); // Create and register a mouse listener with each image node. This // listener is responsible for animating an image node's scaling // from its original size to a small fraction of that size, or // vice-versa. SGMouseListener listener; listener = new SGMouseAdapter () { Point2D global, local; { // Create the global and local Point2D // objects only once, to reduce garbage // collection. global = new Point2D.Double (0, 0); local = new Point2D.Double (0, 0); } public void mouseMoved (MouseEvent me, SGNode n) { // Obtain the node's animation clip for // performing scaling. Clip clip; clip = (Clip) n.getAttribute ("doScale"); // An IllegalStateException is thrown if // clip.start() is invoked when the clip is // already running. The following test avoids // this exception. if (clip.isRunning ()) return; // Convert the mouse event's coordinates to // node-relative coordinates. global.setLocation (me.getX (), me.getY ()); n.globalToLocal (global, local); // Reduce the area in which mouse movements // trigger animations -- large areas result // in an image repeatedly shrinking and // expanding as the mouse moves over the // image. Rectangle2D bounds = n.getBounds (); double x = bounds.getX (); double y = bounds.getY (); double w = bounds.getWidth (); double h = bounds.getHeight (); if (local.getX () < x+w/4.0 || local.getX () > x+3.0*w/4.0) return; if (local.getY () < y+h/4.0 || local.getY () > y+3.0*h/4.0) return; // Start the animation. clip.start (); } }; imageNode.addMouseListener (listener); // Load next image. try { BufferedImage origImage = ImageIO.read (new File (name)); imageNode.setImage (origImage); imageNode.setID ("imageNode: SGImage"); // Make image node a child of a scaling node so that the image // node can be scaled up/down. SGTransform.Scale scaleNode; scaleNode = SGTransform.createScale (1.0, 1.0, imageNode); scaleNode.setID ("scaleNode: SGTransform.Scale"); // Make the scaling node a child of a translation node so that // the image doesn't overwrite the previous image. SGTransform.Translate xlateNode; xlateNode = SGTransform.createTranslation (xOffset, 0, scaleNode); xlateNode.setID ("xlateNode: SGTransform.Translate"); // Make sure image appears to the right of the previous image. xOffset += origImage.getWidth (); // Add translation node grandparent to the group. imageNodes.add (xlateNode); // Create a scaling clip to perform horizontal scaling. final Clip clip = Clip.create (SCALE_TIME, scaleNode, "ScaleX", 1.0, SCALE_DOWN_LIMIT); // Clip's create() method implicitly creates a timing target // that's repeatedly notified during the horizontal scaling. A // second target must be added to the Clip to perform vertical // scaling -- the create() method can only deal with one // property (and with a single argument) at a time. BeanProperty<Double> bp; bp = new BeanProperty<Double> (scaleNode, "ScaleY"); clip.addTarget (KeyFrames.create (bp, 1.0, SCALE_DOWN_LIMIT)); // Add a third target whose end() method is invoked when the // clip finishes. The end() method reverses the clip's // direction in preparation for the next mouseMoved() event // over the image. clip.addTarget (new TimingTargetAdapter () { public void end () { // Reverse the clip's direction for the // next animation. if (clip.getDirection () == Clip.Direction.FORWARD) clip.setDirection (Clip.Direction. BACKWARD); else clip.setDirection (Clip.Direction. FORWARD); } }); // Store the animation clip for later access. imageNode.putAttribute ("doScale", clip); } catch (Exception e) { System.err.println ("Image loading error: "+e); } } // Establish the scene. panel.setScene (imageNodes); // Dump the scene graph hierarchy to the standard output. dump (panel.getScene (), 0); // Install the panel into the Swing hierarchy, pack it to its preferred // size, and don't let it be resized. Furthermore, center and display // the main window on the screen. f.setContentPane (panel); f.pack (); f.setResizable (false); f.setLocationRelativeTo (null); f.setVisible (true); } public static void dump (SGNode node, int level) { for (int i = 0; i < level; i++) System.out.print (" "); System.out.println (node.getID ()); if (node instanceof SGParent) { java.util.List<SGNode> children = ((SGParent) node).getChildren (); Iterator<SGNode> it = children.iterator (); while (it.hasNext ()) dump (it.next (), level+1); } } } // JSGPanel has been subclassed in order to properly center the scene within // this Swing component. class CenteringSGPanel extends JSGPanel { private SGNode sceneNode; private SGTransform.Translate centeringTNode; @Override public void doLayout () { if (sceneNode != null) { Rectangle2D bounds = sceneNode.getBounds (); centeringTNode.setTranslateX (-bounds.getX ()+ (getWidth ()-bounds.getWidth ())/2.0); centeringTNode.setTranslateY (-bounds.getY ()+ (getHeight ()-bounds.getHeight ())/2.0); } } @Override public void setScene (SGNode sceneNode) { this.sceneNode = sceneNode; centeringTNode = SGTransform.createTranslation (0f, 0f, sceneNode); centeringTNode.setID ("centeringTNode: SGTransform.Translate"); super.setScene (centeringTNode); } }
Listing 3 creates three instances of the SGImage class, which describes a scene graph node that renders an image, and stores a separate image (that's loaded via the Image I/O API) in each instance by invoking the SGImage public void setImage(Image image) method. (If you subsequently need to access this image, you can retrieve it via the companion public final Image getImage() method.)
After populating an SGImage node with the loaded image, the listing creates a scaling node, making the image node its child. When the animation performs scaling, that operation will be applied to the image node. Similarly, the scaling node is made a child of a translation node, so that the three image nodes will appear side by side instead of sitting on top of each other.
Next, a Clip is created to animate image scaling via Clip clip = Clip.create (SCALE_TIME, scaleNode, "ScaleX", 1.0, SCALE_DOWN_LIMIT);. When run, this clip repeatedly invokes scaleNode's setScaleX() method to scale the image horizontally—initially, the image is scaled down from its original size to the fractional size determined by SCALE_DOWN_LIMIT.
Because create() can deal only with one property at a time, with the further restriction that the property's setter method can take only one argument, a new timing target (an object based on the com.sun.scenario.animation.TimingTarget interface, and whose methods are invoked at significant moments during the animation) must be created and registered with the animation framework to perform vertical scaling.
The timing target is created via the com.sun.scenario.animation.KeyFrames<T> class's public static <T> KeyFrames<T> create(Property<T> property, T... keyValues) method. This method is passed a com.sun.scenario.animation.BeanProperty<T> instance, whose arguments are scaleNode and "ScaleY".
When the timing target needs to update the "ScaleY" property, it invokes the BeanProperty instance's public void setValue(T value) method, passing the vertical scaling value to value. In turn, BeanProperty invokes scaleNode's setScaleY() method with this value.
The create() method is also passed the 1.0 and SCALE_DOWN_LIMIT property values that are used internally to create a pair of key frames (structures that record property and time values—the property takes on a property value when the animation reaches the associated time value). Additional frames are interpolated (calculated between existing key frames) during the animation.
Because KeyFrames implements TimingTarget, this object can be passed directly to the Clip public void addTarget(TimingTarget target) method. This method registers the timing target so that it will also receive timing events and hence can vertically scale the image during the animation cycle.
The addTarget() method is also called to register a com.sun.scenario.animation.TimingTargetAdapter subclass instance. When an animation cycle ends, this instance's public void end() method is called, reversing the animation direction in preparation for the next cycle, which is initiated when the mouseMoved() method of the image node's registered SGMouseListener is invoked.
After compiling ScaledImages.java and running the resulting application in the same manner as the previous applications, you'll see a window similar to that shown in Figure 3.
Figure 3 Shrink or expand an image by moving the mouse over the image.
You'll also discover, in the standard output, the following hierarchy of nodes that set up a translation to center the scene, and set up a group to store the scene's three image nodes along with their translation and scaling parents:
centeringTNode: SGTransform.Translate imageNodes: SGGroup xlateNode: SGTransform.Translate scaleNode: SGTransform.Scale imageNode: SGImage xlateNode: SGTransform.Translate scaleNode: SGTransform.Scale imageNode: SGImage xlateNode: SGTransform.Translate scaleNode: SGTransform.Scale imageNode: SGImage