Build List of Components in Hierarchy

Build List of Components in Hierarchy

It is sometimes useful to be able to obtain a complete list of the components in a container hierarchy. A getComponents() method is provided in the java.awt.Container class, but it only returns the list of components contained directly by that container. In other words, it does not recursively traverse the component hierarchy. For example, you might have an instance of java.awt.Frame that contains an instance of java.awt.Panel, and the Panel in turn contains components. In this situation, calling getComponents() on the Frame will return the Panel, but not the components contained by the Panel. What’s needed is a method that will traverse the container hierarchy recursively. Although such a method does not exist as part of the Java core classes, you can easily write one. For example:

 public static void traverseTree(Vector list, Container con) {	Component comp;	Component[] comps = con.getComponents();	for (int i = 0; i 

This method is passed a Vector and Container as parameters, and will recursively build the list of components found in the Container, storing references to them in the Vector. It does this by calling itself recursively when it finds a Container within the Container parameter, which ensures that all components will be listed, regardless of how many levels of "nested" containers there are.


Share the Post: