< Zurück | Inhalt | Weiter >

5.4.1 Remove a child Node by reference

It is useful to be able to remove a child Node from its parent Group without knowing the child Node’s index. Unfortunately, because scenegraph Nodes are removed from a Group using void removeChild(int index), there is no easy way to remove a Shape3D object from a Group if you do not know the index at which it was originally inserted. In the following example, I remove a Shape3D object that corresponds to the internal, application−specific data structure. By storing the application−specific data structure in the UserData field of the Shape3D, I can retrieve the index of the Shape3D and remove it from its parent Group object.

ClassificationObject is an application−specific data structure that is stored in each child Node to identify it. To store the ClassificationObject in the Node, use

node.setUserData( classificationObject );

public void removeChildObject( ClassificationObject targetObj )


//we need to remove the object by index, so we have to iterate

//through our objects to find it.

//get an enumeration containing all the child nodes Enumeration enum = getAllChildren();

int nIndex = 0; Node obj = null;

//scan through the child nodes until we find the one that

//corresponds to our data structure. while( enum.hasMoreElements() != false )


obj = (Node) enum.nextElement();

if( targetObj != obj.getUserData() ) nIndex++;

else break;


//if we found the object, we can now remove it by index. if( nIndex <numChildren() )

removeChild( nIndex );


System.out.println( "Failed to find child object during remove operation." );


Note that in the preceding example, the implicit this is an instance of a class derived from Group that has the capability to remove child Nodes based on an internal data structure.