Home > Articles > Programming > Java

Like this article? We recommend

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.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020