Composite Hierarchies

The utils package of the CompositeAPI harbors some utility classes useful when working with hierarchies of composites. Imagine two Composite objects nested within a CompositeGroup lying inside a CompositeView. There may be situations when you have to make transformations from the top-level CompositeView to the deepest embedded Composite or vice versa.

Class CompositeHierarchyUtilities contains some utility functions that will ease your life if you ever have to deal with transformations from or to Composite instances.

Consider a label lying within a BaseComposite that is also lying within a CompositeView. This scenario would look this:

Figure 21.1. A Simple Composite Hierarchy

A Simple Composite Hierarchy

The coordinates of the labels are given relative to the CoordinateSystem of the surrounding BaseComposite.

Due to the fact that transformations, as they are defined in the CompositeAPI, work on arrays of type int, float or double, our first step will be to set up the appropriate array:

int labelCoords[]= {
        label.getLeft(),
        label.getTop(),
        label.getRight(),
        label.getBottom()};

The next step is to apply the coordinate system transformation to our coordinates. In our first step we use the static method getCompositeHierarchyFor(Composite) of class CompositeHierarchyUtilities:

// retrieve the hierarchy for a given BaseComposite
CompositeHierarchyPath path= 
  CompositeHierarchyUtilities.getCompositeHierarchyFor(baseComposite);

The CompositeHierarchyPath instance named path contains the hierarchy of the involved Composite objects, which might look like this:

{ CompositeView { Composite } }

In the next step we retrieve the Transform2D object by calling buildTransform(int direction) on our CompositeHierarchyPath object. This method accepts one of the four constants (no combinations), defined in class CompositeHierarchyUtilities, as a parameter. The meanings of these parameters are as follows:

Now we build the transformation using the appropriate constant:

// build the transformation
Transform2D xform =
  path.buildTransform(
    CompositeHierarchyUtilities.TRANSFORM_FROM_COMPOSITE_TO_VIEW);

// apply it on the label coordinates    
xform.apply(labelCoords);

For the result we have the coordinates of the inlying Primitive label_2 related to the CoordinateSystem of the CompositeView object stored in the array labelCoords.

There is no need to change the code if the Composite object is nested within a group, as illustrated in the following figure:

Figure 21.2. A Simple Composite Hierarchy

A Simple Composite Hierarchy

The CompositeHierarchyPath instance named path contains the hierarchy of involved Composite objects and looks like this:

{ CompositeView { CompositeGroup { Composite, Composite } } }

The tranformation will be built using this deeper path. All remaining steps stay the same. Array labelCoords will contain the coodinates of the given Composite.