tags:

views:

109

answers:

2

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?

A: 

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].

A: 

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)

Telcontar