Starting with the skeleton, import Swing's
tree
package.
Next, create a set of DefaultMutableTreeNode
objects in the
TreeExample
constructor, one for each node in the class hierarchy:
Component
Container
Box
JComponent
AbstractButton
JButton
JMenuItem
JToggleButton
JLabel
... [literally "..."]
Use constructs such as:
DefaultMutableTreeNode component =
new DefaultMutableTreeNode("Component");
Once you've created all the nodes, add them to each other to construct the
hierarchy.
DefaultMutableTreeNode
contains an add
method that defines the children of a node.
Once you have the hierarchy setup, create a class that implements
TreeSelectionListener
.
Have it print the label of the selected
cell and the full path to the cell.
Once you've defined a TreeSelectionListener
class, create an
instance of it.
Create a TreePanel
and pass it the root of your component
hierarchy tree and the TreeSelectionListener
. Add the panel
to the frame. You'll finish up the TreePanel
description next.
The TreePanel
class will offer the visual representation of
the tree. Modify the constructor of
TreePanel
so that it creates a
JTree
called tree
attached to the root
passed in to the constructor.
Change the lineStyle
client property of the tree to
Angled
.
Associate the TreeSelectionListener
to the JTree
if it is non-null.
Then, create a JScrollPane
object, and place the tree in it.
Save everything and compile the program. Then run it to see the results.