If I have a String[] such as { "root", "two", "1" } how can I get the DefaultMutableTreeNode from my JTree that is represented by this “path”?
For example if my JTree looks like this:
root
one
1
2
two
1 <-- I want this node
2
Assume all nodes are DefaultMutableTreeNodes.
First, you need to fetch the tree model with
getModel()method. Once you have the model, it has thegetRoot()method, to fetch the root of the tree. After that, you can follow with calls togetChild(Object parent, int index)and check if any of the children has the same name as the one provided in the String array. If you find such one, you can again callgetChild(Object parent, int index), etc… until you arrive at the last String from the array. Then you have the corresponding tree node. You need to actually cast the tree nodes to DefaultMutableTreeNode, as the TreeModel uses Object as the tree elements (for pre-1.7 Java).