Search code examples
javaswingjtree

jtree couldnt get index of specific node


i have jTree (for example):

-paper
    -coated
    -glossy
        -hummermill
        -quatro
        -springhill
    -matte

when i select springhill i get index of 5, but i dont want to count from the root(paper) (that includes parents and other nodes outside the glossy), i want to start counting from hummermill so i try to get index of 2.

i used tree.getLeadSelectionRow() and get int value of 5; also i use node.getIndex(node) but here i dont get anything normal (0,3,-1). I try all variations of all metods there is for node and tree and find nothing helpfull. plese help!


Solution

  • You have to find the index of node from its parent

      DefaultMutableTreeNode node=(DefaultMutableTreeNode) jTree1.getSelectionPath().getLastPathComponent();
    
      System.out.println(node.getParent().getIndex(node));