Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: Java
Expertise: Intermediate
Jun 25, 1999

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 < comps.length; i++) {
		if (comps[i] instanceof Container) {
			traverseTree(list, (Container)comps[i]);
		}  //  if (comps[i] instanceof Container)
		list.addElement(comps[i]);
	}  //  for (int i = 0; i < comps.length; i++)
}  //  public static void traverseTree()

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.

Brett Spell
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap