Java Reference
In-Depth Information
public JTree(TreeModel value)
JTree tree = new JTree(aTreeModel);
public JTree(TreeNode value)
JTree tree = new JTree(aTreeNode);
public JTree(TreeNode value, boolean asksAllowsChildren)
JTree tree = new JTree(aTreeNode, true);
The first of the constructors is the no-argument variety. Surprisingly, it has a default data
model with some nodes in it (see Figure 17-1). Normally, you would change the data model of
the default tree after creation with setModel(TreeModel newModel) .
The next three constructors seem to belong together. Creation of a JTree from a Hashtable
made up of key/value pairs uses the set of keys for the nodes and values for the children, whereas
creation from an array or Vector uses the elements as the nodes. This may seem to imply that
the tree is only one level deep, but actually the tree can be infinitely deep if the key or element
itself is in a Hashtable , an array, or a Vector .
The remaining three constructors use the custom data structures of JTree , which will be
explained later in this chapter. By default, only those nodes that have children are leaf nodes.
However, trees can be constructed with partial nodes that won't get children until later. The
last of these three constructors causes a method to be called when you try to open a parent
node, instead of the parent node just looking for child nodes.
Tip If the value for a key in a Hashtable is another Hashtable , array, or Vector , you can create a multi-
level tree by using the top-level Hashtable as the constructor argument.
As I mentioned, using a Hashtable , an array, or a Vector as the argument in the constructor
tree does, in fact, allow you to create multilevel trees. There are two minor problems with this,
however: the root node isn't visible, and it automatically has a data element of root . The text
label for any other nodes of type Hashtable , array, or Vector is the result of toString() . The
default text is not desirable in any of these three instances. You get either the results of the
toString() method of the Object class for an array or a label that includes a list of all the elements
in the Hashtable or Vector . In the case of an Object array, the output would look something like
[Ljava.lang.Object;@fa8d8993 . This is certainly not something you want to show a user.
Although you cannot override toString() (because there is no array class to subclass), you
can subclass Hashtable or Vector to provide a different toString() behavior. Offering a name
to the constructor of this new class allows you to provide a text label to use in the tree when the
Hashtable or Vector is not the root node. The class shown in Listing 17-1 defines this behavior
for a Vector subclass. In addition to the constructor providing a name, the class also adds a
constructor that initializes the Vector to the contents of an array.
 
Search WWH ::




Custom Search