Nodes
Scene graphs are expressed as collections of nodes that are organized into tree or graph structures. For example, Project Scene Graph organizes a scene graph's nodes into a tree. Each node defines a local coordinate system (x increases to the right; y increases downward) and is an instance of a class that subclasses the abstract com.sun.scenario.scenegraph.SGNode class. SGNode's methods include the following:
- public void addFocusListener(SGFocusListener listener): Register a focus listener, which implements the com.sun.scenario.scenegraph.event.SGFocusListener interface, with this node to receive notification of keyboard focus gained and lost events.
- public void addKeyListener(SGKeyListener listener): Register a key listener, which implements the com.sun.scenario.scenegraph.event.SGKeyListener interface, with this node to receive notification of key pressed, released, and typed events.
- public void addMouseListener(SGMouseListener listener): Register a mouse listener, which implements the com.sun.scenario.scenegraph.event.SGMouseListener interface, with this node to receive notification of mouse clicked, dragged, entered, exited, moved, pressed, released, and wheel moved events.
- public void addNodeListener(SGNodeListener listener): Register a node listener, which implements the com.sun.scenario.scenegraph.event.SGNodeListener interface, with this node to receive notification of node bounds changed events.
- public boolean contains(java.awt.geom.Point2D point): Return true if the point argument's coordinates are contained within this node's bounds—the coordinates must be specified in the local/untransformed coordinate space of this node. An IllegalArgumentException is thrown if null is passed to point. The test is based on geometry (not visibility).
- public final Object getAttribute(String key): Return the value associated with this node's key attribute—null returns if the attribute doesn't exist.
- public final java.awt.geom.Rectangle2D getBounds(): Return this node's bounding box in the coordinate space inherited from the node's parent. This convenience method is equivalent to calling getBounds(null)—see the method below.
- public abstract Rectangle2D getBounds(java.awt.geom.AffineTransform transform): Return this node's bounding box after applying the specified transform.
- public final String getID(): Return this node's textual identifier. Listing 1's dump() method invokes this method to obtain each node's ID in the hierarchy.
- public SGParent getParent(): Return this node's parent node or null if this node is the root node.
- public JSGPanel getPanel(): Return this node's scene graph container, which makes it possible to access the root node via JSGPanel's public final SGNode getScene() method.
- public Point2D globalToLocal(Point2D global, Point2D local): Transform a point (specified by global) from the root node's coordinate system (known as the global coordinate system) to this node's local coordinate system. The argument passed to global must not be null. If null is passed to local, a new Point2D object is created and returned following the transformation. Otherwise, the result is stored in local.
- public Point2D localToGlobal(Point2D local, Point2D global): Transform a point (specified by local) from this node's local coordinate system to the root node's coordinate system (known as the global coordinate system). The argument passed to local must not be null. If null is passed to global, a new Point2D object is created and returned following the transformation. Otherwise, the result is stored in global.
- public final void putAttribute(String key, Object value): Store an attribute, identified by key and having the associated value, in this node—you'll see the usefulness of attributes later in this article.
- public void removeFocusListener(SGFocusListener listener): Remove the focus listener that was previously registered with this node.
- public void removeKeyListener(SGKeyListener listener): Remove the key listener that was previously registered with this node.
- public void removeMouseListener(SGMouseListener listener): Remove the mouse listener that was previously registered with this node.
- public void removeNodeListener(SGNodeListener listener): Remove the node listener that was previously registered with this node.
- public final void requestFocus(): Request that this node receive the keyboard focus.
- public final void setID(String id): Set this node's textual identifier. Listing 1 uses this method to assign a unique ID to each node in the hierarchy.
Listing 1 accesses getBounds() in the context of createBorderedNode()'s Rectangle2D nodeR = node.getBounds (); statement. After invoking getBounds() to fetch the origin and dimensions of its node argument, createBorderedNode() uses these values to create a border node that will appear behind and surround the text node that displays Hello, PSG!
The SGNode Class Hierarchy
SGNode is the superclass of two abstract subclasses: SGLeaf and SGParent. SGLeaf serves as the superclass for subclasses that know how to respond to mouse and keyboard input, and also know how to paint themselves. In contrast, SGParent serves as the superclass for subclasses that act as containers for child nodes.
Moving down the SGLeaf branch of this class hierarchy, you discover three subclasses: the abstract SGAbstractShape class, and the non-abstract SGComponent and SGImage classes. The former class is the superclass for shape-oriented subclasses, and the latter two classes allow Swing components and images to be added to a scene graph.
Below SGAbstractShape, you find SGShape and SGText. SGShape lets you add instances of java.awt.Shape implementations (such as Rectangle2D, Ellipse2D, GeneralPath, and other java.awt.geom classes) to a scene graph, whereas SGText lets you add a single line of text to the scene graph.
If you move down the SGParent branch, you discover the non-abstract SGFilter and SGGroup subclasses, and the abstract SGWrapper subclass. SGFilter and its subclasses represent visual state (such as 2D transforms and composition), SGGroup allows a group of nodes to be transformed as a whole, and SGWrapper is related to JavaFX (as you'll see).
SGFilter's subclasses include SGClip (add a clipping shape), SGComposite (add opacity: transparent, translucent, or opaque), SGEffect (add a visual effect), SGImageOp (add a java.awt.image.BufferedImageOp instance), SGRenderCache (add a node that caches the rendering of a subtree in a BufferedImage for performance), and SGTransform (add a transform, such as a rotation).
A Detailed Look at Six SGNode Subclasses
Listing 1 references the SGNode SGGroup, SGShape, SGText, SGComposite, SGTransform, and SGTransform.Translate subclasses. Let's delve into each class to learn more about how Listing 1 works.
The createAndShowGUI() method instantiates SGGroup (SGGroup sceneNode = new SGGroup ();) to specify a group as the scene graph's apparent root node. Several calls are made to the SGGroup public final void add(SGNode child) method to add a group node containing border shape and text nodes, an effect node, and a composite node to the root. This class also includes these methods:
- public void add(int index, SGNode child): Add the child node to the group at the location specified by index.
- public final Rectangle2D getBounds(AffineTransform transform): Return the group's bounding box after applying the specified transform.
- public final java.util.List<SGNode> getChildren(): Return the group's child nodes in a List collection.
- public final void remove(int index): Remove the node located at index from the group.
- public void remove(SGNode child): Remove the child node from the group.
The createBorderedNode() method also instantiates SGGroup (SGGroup borderedNode = new SGGroup ();) to group a "rectangular shape" node with a "line of text" node. When adding nodes to a group, keep in mind that order matters. For example, if you add the text node before the shape node, the rectangle is rendered last, possibly hiding the text (depending on rectangle location, size, and opacity).
Along with SGGroup, createBorderedNode() instantiates SGShape (SGShape borderNode = new SGShape ();). It then invokes the following SGShape methods to establish a rectangle with a rounded yellow border and reddish interior, and to take advantage of antialiasing so that the rounded corners look round:
- public void setShape(Shape shape): Assign a Java Shape instance to this node. For example, borderNode.setShape (new RoundRectangle2D.Double (x, y, w, h, a, a)); installs a rectangle with rounded corners. You can invoke the companion public final Shape getShape() method to retrieve the shape.
If the shape object is subsequently modified, the application must reinvoke setShape() to ensure that the node state is properly updated.
- public void setFillPaint(java.awt.Paint fillPaint): Assign a gradient, solid color, or some other kind of Paint to this node for rendering its interior. For example, borderNode.setFillPaint (new Color (0x660000)); uses a solid shade of red to paint the interior. To retrieve the current fill Paint, invoke the companion public final Paint getFillPaint() method.
- public void setDrawPaint(Paint drawPaint): Assign a gradient, solid color, or some other kind of Paint to this node for rendering its outline. For example, borderNode.setDrawPaint (new Color (0xFFFF33)); uses a solid shade of yellow to paint the outline. To retrieve the current draw Paint, invoke the companion public final Paint getDrawPaint() method.
- public void setDrawStroke(java.awt.Stroke drawStroke): Assign a stroke to this node for rendering its outline style (such as dashed) and width. For example, borderNode.setDrawStroke (new BasicStroke ((float) (BORDERWIDTH/2.0))); specifies a solid outline with BORDERWIDTH/2.0 as the width. To retrieve the current draw Stroke, invoke the companion public final Stroke getDrawStroke() method.
- public final void setMode(SGAbstractShape.Mode mode): Specify whether only the shape's outline will be rendered (SGAbstractShape.Mode.STROKE), only the shape's interior will be rendered (SGAbstractShape.Mode.FILL), or both the outline and interior will be rendered (SGAbstractShape.Mode.STROKE_FILL). I chose this latter setting via borderNode.setMode (SGAbstractShape.Mode.STROKE_FILL);. The companion method, public final SGAbstractShape.Mode getMode(), returns the current shape-rendering mode.
- public void setAntialiasingHint(Object hint): Set this node's KEY_ANTIALIASING rendering hint to RenderingHints.VALUE_ANTIALIAS_ON, RenderingHints.VALUE_ANTIALIAS_OFF, or RenderingHints.VALUE_ANTIALIAS_DEFAULT. For example, borderNode.setAntialiasingHint (RenderingHints.VALUE_ANTIALIAS_ON); activates antialiasing. The companion public Object getAntialiasingHint() method returns the current setting.
Because the fill, draw, stroke, and mode methods are inherited from SGAbstractShape, they're also available to SGText. For example, createAndShowGUI() sets a text node's fill color to white (textNode.setFillPaint (Color.WHITE);) after creating this node (SGText textNode = new SGText ();). Also, createAndShowGUI() invokes the following SGText methods:
- public void setText(String text): Assign a single line of text to this node. The companion public final String getText() method returns this text. Example: textNode.setText ("Hello, PSG!");.
- public void setFont(java.awt.Font font): Assign the font for rendering this node's text. You can obtain the current font via the companion public final Font getFont() method. Example: textNode.setFont (new Font ("SansSerif", Font.PLAIN, 96));.
- public void setAntialiasingHint(Object hint): Set this node's KEY_ANTIALIASING rendering hint to RenderingHints.VALUE_ANTIALIAS_ON, RenderingHints.VALUE_ANTIALIAS_OFF, or RenderingHints.VALUE_ANTIALIAS_DEFAULT. For example, borderNode.setAntialiasingHint (RenderingHints.VALUE_ANTIALIAS_ON); activates antialiasing. The companion public Object getAntialiasingHint() method returns the current setting.
Additionally, SGText provides useful methods (which are not used by HelloPSG) for obtaining a text node's bounding box and for setting/obtaining its location and vertical alignment:
- public final Rectangle2D getBounds(AffineTransform transform): Return this node's bounding box after applying the specified transform.
- public void setLocation(Point2D location): Set this node's origin to the coordinates specified by location. The companion public final Point2D getLocation() method returns this origin. Alternatively, you can invoke public final Point2D getLocation(Point2D rv), specifying rv as the object in which to store the coordinates.
- public void setVerticalAlignment(SGText.VAlign verticalAlignment): Determine what constitutes the vertical component of this node's origin: SGText.VAlign.BASELINE (the text's baseline), SGText.VAlign.BOTTOM (the bottom of the lowest descender), or SGText.VAlign.TOP (the top of the highest ascender). The companion public final SGText.VAlign getVerticalAlignment() method returns this setting.
After creating effectNode (I discuss effects later), createAndShowGUI() creates an instance of the SGComposite class (SGComposite compNode = new SGComposite ();) to specify the opacity (compNode.setOpacity (1.0f);—opaque) of a child node (compNode.setChild (effectNode);). Project Scene Graph ensures that effectNode's drop shadow is rendered at this opacity level.
SGComposite provides a public void setOpacity(float opacity) method to specify the opacity (0.0f means transparent, 1.0f means opaque, and anything in between means translucent). The current opacity setting can be returned by invoking this class's companion public float getOpacity() method.
The node to which this opacity will be applied is specified by public void setChild(SGNode child), which is one of the methods inherited from SGFilter. If you need to determine which child node has been assigned to the SGComposite instance, you can invoke the companion public final SGNode getChild() method.
The setChild() method physically rearranges the order in which nodes appear in the scene graph. For example, if you were to comment out the lines effectNode.setChild (textNode); and compNode.setChild (effectNode); in Listing 1, you would observe a hierarchy that reflects the actual node-insertion order—not the order needed to perform proper rendering (which I showed earlier):
centeringTNode: SGTransform.Translate sceneNode: SGGroup borderedNode: SGGroup borderNode: SGShape textNode: SGText effectNode: SGEffect compNode: SGComposite
The final classes to consider are SGTransform and SGTransform.Translate, which CenteringSGPanel uses to ensure that the scene is properly centered horizontally and vertically within the containing frame window's client area. Its overridden setScene() method invokes the following method to return an SGTransform.Translate instance:
public static SGTransform.Translate createTranslation(double tx, double ty, SGNode child)
- tx and ty specify the initial translation factor.
- child specifies the node to which the translation is applied.
For example, centeringTNode = SGTransform.createTranslation (0f, 0f, sceneNode); creates a Translate node that performs no initial translation on sceneNode and stores the instance in centeringTNode. This node is then specified to Project Scene Graph as the scene's actual root node via super.setScene (centeringTNode);.
CenteringSGPanel's overridden doLayout() method takes advantage of centeringTNode to invoke the Translate public abstract void setTranslateX(double tx) and public abstract void setTranslateY(double ty) methods to perform the actual translations horizontally and vertically:
Rectangle2D bounds = sceneNode.getBounds (); centeringTNode.setTranslateX (-bounds.getX ()+ (getWidth ()-bounds.getWidth ())/2.0); centeringTNode.setTranslateY (-bounds.getY ()+ (getHeight ()-bounds.getHeight ())/2.0);
After retrieving the bounding box for the original root node (the SGGroup instance), doLayout() maps the node's upper-left origin to (0, 0) and then calculates an appropriate location for the node's upper-left corner, so that the scene will be centered. The setTranslateX() and setTranslateY() methods save this information so that the scene is centered during rendering.