Useful Code of the Day: Get TreePath by object
If you've ever had a JTree in your application, you've probably had this problem:
You have the tree. You have an object hierarchy, which you loop through on initialization and add nodes for each object. Now you want to use a method in the tree which requires a TreePath as a parameter... But you don't have a TreePath, you just have an object somewhere in the hierarchy that you put in the tree.
So how do you get a TreePath for that object? Maybe this?
TreePath tp =new TreePath(new DefaultMutableTreeNode(grandparent));
tp = tp.pathByAddingChild(new DefaultMutableTreeNode(parent));
tp = tp.pathByAddingChild(new DefaultMutableTreeNode(object));
tree.makeVisible(tp);
This just doesn't work. While it looks good, the TreePath does not match a real path in the tree.
Of course, you could keep a map of objects and the nodes they were put in, but if you're going to do a lot of editing of the tree's structure, you have to add code to maintain that map of objects. This is just more work, and thus opens room for bugs.
Instead, the method below will get a valid TreePath for a specified object under a node. It is assumed that at least, you'll have a reference to the root node, e.g.:
DefaultMutableTreeNode root = (DefaultMutableTreeNode)tree.getModel().getRoot();
TreePath tp = getTreePath(root, obj);
tree.makeVisible(tp);
This code uses DefaultMutableTreeNode as basis. (If you have another TreeNode class, it'll have to have a way to get the internal object and the path to it's root.)
/**
* Gets the <CODE>TreePath</CODE> for the specified object under the
* specified node. This will search all children under the node until
* it finds the object or runs out of child nodes.
*
* @param node the root node
* @param objthe object to find
* @return the tree path to the object or <CODE>null</CODE>
*/
public TreePath getTreePath(DefaultMutableTreeNode root, Object obj){
if(root.getUserObject().equals(obj)){
returnnew TreePath(node.getPath());
}
for(int i = 0; i < root.getChildCount(); i++){
TreePath tp = getTreePath(
(DefaultMutableTreeNode)root.getChildAt(i), obj);
if(tp !=null){
return tp;
}
}
returnnull;
}
"Useful Code of the Day" is supplied by the person who posted this message. This code is not guaranteed by any warranty whatsoever. The code is free to use and modify as you see fit. The code was tested and worked for the author. If anyone else has some useful code, feel free to post it under this heading.

