O'Reilly logo

Java Examples in a Nutshell, 3rd Edition by David Flanagan

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Displaying Trees

The JTree component is used to display tree-structured data. If your data is in the form of nested arrays, vectors, or hashtables, you can simply pass the root node of the data structure to the JTree constructor, and it displays it. Tree data is not typically in this form, however. In order to display data that is in another form, you must implement the javax.swing.Tree.TreeModel interface to interpret the data in a way the JTree component can use it.

Example 11-20 shows a listing of ComponentTree.java, a JTree subclass that uses a custom TreeModel implementation to display the containment hierarchy of an AWT or Swing GUI in tree form. The class includes a main( ) method that uses the ComponentTree class to display its own component hierarchy, as shown in Figure 11-17. As with the previous JTable example, the key to this example is the TreeModel implementation. The main( ) method also illustrates a technique for responding to tree node selection events.

The ComponentTree application

Figure 11-17. The ComponentTree application

Example 11-20. ComponentTree.java

package je3.gui; import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.event.*; import javax.swing.tree.*; /** * This class is a JTree subclass that displays the tree of AWT or Swing * component that make up a GUI. **/ public class ComponentTree extends JTree { /** * All this constructor method has ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required