- The Tree Control
- Tree Appearance
- The TreeNode Interface
- The MutableTreeNode Interface
- The DefaultMutableTreeNode Class
- The TreePath Class
- What is a Leaf?
- Tree Expansion and Traversal
- Expanding and Collapsing Nodes under Program Control
- Tree Expansion Events
- Making Nodes Visible
- Controlling Node Expansion and Collapse
- Tree Model Events
- Implementation Plan for the File System Control
- File System Tree Control Implementation
- Using the File System Tree Control
- Custom Tree Rendering and Editing
- Customizing the Default Tree Cell Renderer
- ToolTips and Renderers
- Custom Cell Editors
- Controlling Which Nodes Can Be Edited
- Controlling Editability by Subclassing JTree
- Programmatic Control of Editors
- Editing Trees with Custom User Objects
- The valueForPathChanged Method
- The Tree Implementation
- The Cell Editor
- The Cell Renderer
- Summary
Tree Appearance
To emphasize how dependent the appearance of a tree and its nodes are on the selected look-and-feel, let's look at some of the possible variations. Figure 101 shows a tree with the Metal look-and-feel selected. The same tree in the Windows look-and-feel is shown in Figure 102, while the Motif version can be seen in Figure 103.
It's pretty evident that there are differences between these figures and Figure 101. As you can see, Windows and Motif use boxes to indicate nodes that have children. When the children are invisible, the expansion box has a plus sign to indicate that there is more of the tree to be viewed; when you open such a node to show its children, the plus sign changes to a minus sign, as you can see in the case of the C:\WINDOWS\SYSTEM node. The icons are also subtlly different and the line styles vary between look-and-feel implementations.
It is even possible to have different representations of the same tree within a single look-and-feel. The tree has a client property called lineStyle that is used to control the lines drawn between nodes. This property is currently supported only by the Metal look-and-feel, but there is nothing about the mechanism used to implement it that binds it to a single look-and-feel, so you may find it implemented more widely in the future. The lineStyle property has three possible values, listed in Table 10-1.
Table 101 LineStyle Settings
Setting |
Effect |
None |
No lines are drawn anywhere on the tree. |
Angled |
Vertical lines between nodes at the same level, horizontal line to child node. |
Horizontal |
A single horizontal line between nodes immediately attached to the root node. This is the default setting. |
Figure 101 shows a tree with the Angled setting, which is the most natural way to represent a file system and is most like the appearance of Windows and Motif trees. This configuration can be obtained using code like this:
Jtree tree = new Jtree() ;
Figure 102 A tree as drawn by the Windows look-and-feel
Figure 103 A Motif tree.
Tree.putClientProperty("Jtree.lineStyle", "Angled");
Similar code is required to obtain the other two possible effects. The same tree rendered with lineStyle set to None is shown in Figure 104 and with lineStyle set to Horizontal in Figure 105. Because None is the default, all of your trees will look like the one in Figure 104 if you don't explicitly select a lineStyle. Since lineStyle is ignored by look-and-feel implementations that don't provide it, it is always safe to set a specific value no matter which look-and-feel is selected.
Tree Node Selection
The mouse can be used to select an item from the tree by clicking on the icon or the text. Clicking twice on either of these is the same as clicking on the expansion handlethe node either expands or collapses depending on its current state. The ability to make a selection is one of the main reasons for using a tree control. As you'll see, you can attach listeners that receive notifi-cation when a selection is made and you can also arrange to be notified when part of the tree is expanded or collapsed or is about to do so.
Figure 104 A Metal tree with line style "None."
Elements of the Tree
Now let's turn to how a tree is represented in terms of data structures. The only elements of any substance in a tree are the nodes themselvesthe way in which these nodes relate to each other is represented by references from one node to another. The JTree control doesn't directly manage the nodes themselves, or remember how they are organized. Instead, it delegates this to its data model.
As with the other Swing components, JTree deals mainly with generic objects that are represented in Java by an interface. For example, any class can be used as a data model for the tree, so long as it implements the Tree-Model interface and any class can participate in the model as a node in the tree so long as it implements the interface TreeNode. This design pattern has been shown before in connection with JComboBox and JList, which have data models specified as interfaces and concrete implementations of those interfaces that are used by default. The JTree (and, to some extent JTable) is a little different from JComboBox and JList in that it is not really good enough to just implement the TreeNode and TreeModel interfaces. The default implementations of these interfaces in the Swing tree package provide facilities far beyond those specified by TreeNode and TreeModel. Furthermore, in many cases, these extra facilities can be accessed directly through the model or indirectly via the JTree object and there will be a loss of functionality if classes that only implement the minimal interface are used instead of the default ones. In practice, tree nodes are most likely to be instances of the class DefaultMutableTreeNode, while the model will probably be derived from DefaultTreeModel. For specific, lightweight uses of the tree where the full functionality of DefaultMu-tableTreeNode and DefaultTreeModel are not required, it might be useful to develop less functional implementations.
Figure 105 A Metal tree with line style "Horizontal."
JTree is unlike JComboBox and JList in another way. When you create either of the latter two, you populate the model and then wait for a selection. The item that is retrieved from the control as the user's selection is of the same type as the data held within the model itself. For example, a list box populated with Strings would return a selected item of type String. With JTree, things are not so simple. The model deals in terms of nodes, but the user interface to the tree uses a class called TreePath and the immediate result of a selection is one or more TreePaths. As you'll see later, there is a way to map from a TreePath to the corresponding TreeNode, which means that it is possible, from an event listener, to get back to the original node in the data model. This node is not, however, of any direct use to the selection event handler unless some information has been stored with the node that is of meaning to the user of the tree. Suppose, for example, that you construct a tree that shows the content of a file system in a file open dialog and the user double-clicks on an item to have it returned to the tree user as the selected file. There are two ways that the interface to the user of this tree could be builteither the name of the selected file would be returned, or alternatively you could choose to return an object that represents the file that was stored with the file's node when the tree was created. The second of these alternatives is obviously more powerful. To make such an implementation possible, the tree nodes allow you to store a reference to an arbitrary object, called the user object, with each node. How you use this is up to youyou might just choose to make it the file's name, or it might be a java.io.File object for the file.
Creating a Tree
JTree has no less than seven constructors, most of which allow you to initialize the data model with a small quantity of data taken from the more common data collection classes in the JDK:
public JTree(); public JTree(Hashtable value); public JTree(Vector value); public JTree(Object[] value); public JTree(TreeModel model); public JTree(TreeNode rootNode); public JTree(TreeNode rootNode, boolean askAllowsChildre);
The first constructor gives you a tree with a small data model already installed; this can be useful when you write your first program that uses a tree, but after that you'll probably never use it again. The next three constructors initialize the tree from a Hashtable, a Vector, and an array of arbitrary objects. Since all of these are flat data structures, the resulting tree is also flat, consisting of a root node and the data from the object passed to the constructor attached to it, with one node per entry in the table, vector or array. Figure 106 shows a tree created from a Hashtable containing five entries.
Figure 10-6 A tree created from a Hashtable.
The code that was used to create this tree is shown in Listing 10-1 and can be run using the command
java JFCBook.Chapter10.HashHandleTree.
Listing 101 Creating a Tree with a Hashtable
package JFCBook.Chapter10; import javax.swing.*; import javax.swing.tree.*; import java.util.*; public class HashHandleTree { public static void main(String[] args) { JFrame f = new JFrame("Tree Created From a Hashtable"); Hashtable h = new Hashtable(); h.put("One", "Number one"); h.put("Two", "Number two"); h.put("Three", "Number three"); h.put("Four", "Number four"); h.put("Five", "Number five"); JTree t = new JTree(h); t.putClientProperty("JTree.lineStyle", "Angled"); t.setShowsRootHandles(false); f.getContentPane().add(t); f.pack(); f.setVisible(true); } }
As you can see from Figure 106, the tree displays all of the items from the Hashtable. Each item has been turned into a leaf node and added directly beneath the root node of the tree. However, since a root node was not explicitly supplied, the tree doesn't display one. This is a common feature amongst trees created with the second, third, and fourth constructors. A consequence of this is that you can't collapse this tree. You can force the root node to be displayed by using the JTree setRootVisible method:
t.setRootVisible(true);
This would show the root node as an open folder labeled root, with an expansion icon to the left of it. If you don't want to show the expansion icon, you can disable it using setShowsRootHandles:
t.setShowsRootHandles(false);
Figure 107 shows two trees, both with the root node visible. The left-hand tree was created with setShowsRootHandles(true) and the right one with setShowsRootHandles(false).
Figure 107 A tree with the root visible.
You can expand or collapse the tree by double-clicking on the root folder or its label. You can also use the keyboard to navigate the tree and open or close nodes. If you select the root node, you can use the down arrow key to move down the set of child nodes and the up key to move back up again. When a node that has children is selected and closed, the right arrow key will open it. Similarly, you can use the left arrow key on an open branch node to close it.
In cases like this where the root node was created automatically, the arbitrary label root is assigned to it. You can, if you wish, change this label or remove it entirely. You'll see how to do this later.
You'll notice that the items in the tree are not ordered in a particularly sensible way. This happens because Hashtables don't maintain the order of the items that you place into them. The tree is constructed by getting an enumeration of the items in the Hashtable, which doesn't guarantee any particular ordering. If you care about the order in which the data is displayed, you should use a Vector or an array.
Most trees will be created using one of the last three constructors, which require a complete tree model or at least the root node to have already been constructed. If you choose to supply a model, you can use the Swing DefaultTreeModel class, or create your own as long as it implements the TreeModel interface. For most purposes, DefaultTreeModel is more than adequate and, as mentioned earlier, it offers useful facilities over and above the basic interface, many of which will be used in this chapter.