简体   繁体   中英

How to get a specific JTree node given a string array

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 DefaultMutableTreeNode s.

First, you need to fetch the tree model with getModel() method. Once you have the model, it has the getRoot() method, to fetch the root of the tree. After that, you can follow with calls to getChild(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 call getChild(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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM