Loading the tree
It's fairly easy to create a tree and fill it with data:
- Create a tree node. We use standard Swing classes for our model and our nodes,
so it's a DefaultMutableTreeNode.
- Create a model (it's a DefaultTreeModel), passing in the first node, which becomes
the root of the tree.
- Create more nodes and attach them to the model by making them children of the root
or of other nodes already in the model.
- Instantiate a Swing or dbSwing tree and set its model property to your model.
When you write code to do this, you quickly encounter the issues discussed in our
user data object topic. We mention several here. See the comments in
TreeModelMaker.java for more information.
- For each node you create, you have to search the tree to find its parent. It
becomes clear that you need a node ID - something to uniquely identify a node. We
use the full "path" of the node in the tree as its node ID. If you're building a
very large tree, you'll probably want to find a way to add nodes in order, so you
don't have to search the entire tree for each new node's parent.
- A node ID like ours isn't suitable to be the value displayed in the tree component.
It's much too long, and most of it is redundant when the nodes' hierarchy is displayed
visually in the tree. So you add a cell renderer to present a more useful value in
the tree.
- With a deep tree, our node ID will quickly become very long. You might decide
to use a shorter node ID, such as a unique number or a string made by concatenating all
the numeric IDs from the root down to the node. Since you can't extract the text to
display in the tree from such a node ID, you might want to include the desired text
in the node as well. However, Swing and dbSwing trees only know two kinds of user data
object: Strings and other, undifferentiated Objects. Now your user data object is
just an Object. When you define your data object class, you must be sure to override
equals() so dbSwing can successfully compare values in the data set column that your
tree is bound to with values in tree nodes.