简体   繁体   中英

JTree selection

I have a JTree which is 5 level deep, 0, 1, 2, 3, 4 levels. I am interested in level 1's informaton, value or index. is it possible to immediately get level 1' information whenever the selection is below level 1?

If you are interested in the selected level 1 node use the method

JTree.getSelectionPath() 

To get the selected TreePath then check if the TreePath returned has at least 2 elements (first is the root, second the selected level 1 node) with

TreePath.getPathCount()

 If the return>= 2 then use 

TreePath.getPathComponent(1) 

to get the selected level 1 node. (0 index is the root)

If your level 1 nodes are static, you can just keep a reference to them in your tree class. That'll give you a direct way to access those nodes, and you'll have the derived class information available assuming you've used one.

There's also DefaultTreeModel.getChild(...) which would let you get a node by its index under the root node.

If you're trying to go "up" the tree to the level 1 node, you could try getPathToRoot on the tree model. The level 1 node (just under root) would be result[1] .

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