Search code examples
jtree

JTree: Return branch when leaf selected


I am new to JTrees and have a simple question. If I select a leaf, I can return the selected row number by using

int row = getRowForPath(getSelectionPath());

Is there a way to return the path/row for the branch under which my leaf falls? That is, if I have the following tree:

  • Root
    • Fruit
      • Apple
      • Banana
    • Vegetable
      • Lettuce
      • Carrot

And I select "Apple", then I get the row number for "Fruit"?


Solution

  • Invoke getParentPath() on the result returned by getSelectionPath().

    tree.getSelectionPath().getParentPath()
    

    Because getPath() "returns an ordered array of the elements of this TreePath," the penultimate element of the resulting array is the parent. You can see the effect in this complete example; a TreeSelectionListener updates a JTextField as shown below.

    enter image description here