0
votes

I have below Tree structure which is sub class of JTree

enter image description here

When the user selects a node, Time in image above, I need to get the Row index (index value = 3) of Demoscrigo(image above) with respect to Wells not from actual Root. Same index will be used to pre-select the row in other UI.
I can get the selected Object but as the nodes has duplicate entries that is making things difficult.
I have tried below options

    getRowForPath(new TreePath(selectedNode.getPath()))
    getSelectionRows()
    
    this.getModel().getIndexOfChild(userObj, selectedNode);
    JavaClientTreeModel treeModel = (JavaClientTreeModel) this.getModel();
    selectedNode.getLevel()
    
    this.getLastSelectedPathComponent();
    this.getLeadSelectionRow();

But not able to figure out any specific combination. Please suggest me if any other solution is there.

1
If you're using multiple DefaultMutableTreeNodes to create the JTree, the getParent method gets the parent TreeNode. Get the parent in a loop until you get to the node you're looking for. docs.oracle.com/javase/8/docs/api/javax/swing/tree/… docs.oracle.com/javase/tutorial/uiswing/components/tree.htmlGilbert Le Blanc
If you are not using DefaultMutableTreeNodes (most likely you are using them). Simp,y subtract the row of the "new root" from the row of the node.weisj
@GilbertLeBlanc I have used getParent and with few modification, able to achieve row index. Adding my code below. Appreciate your help.jitu13
@weisj subtraction of row does not give proper result when other nodes are expanded.jitu13

1 Answers

0
votes

First fetch the node for which Index need to be calculated by using the below code.
Parameter Type is used to get the above node

public DefaultMutableTreeNode findNode(DefaultMutableTreeNode node, String type){
        Object data = (XXXX) node.getUserObject();
        if(data.getType().equals(type)){
            return node;
        }else if(!node.isRoot()){
            return findNode((DefaultMutableTreeNode) node.getParent(), type);
        }
        return null;
    }

And then use

int rowIndex = node.getParent().getIndex(node);