Reputation: 490
I implemented a JTree and I need to get the index of a selected node.
Im trying to get the index using this code:
tree.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
// This code to get selected index of node
int[] selectionRows = tree.getSelectionRows();
}
});
But the method getSelectionRows returns differents results depending if some nodes were collpased or expanded. For example:
This is my Tree:
If I select one node, like picture after, the getSelectionRows return number 4.
But if some node were collapsed, like picture after, the getSelectionRows return 3.
I need thats always return 4, thats is the number of the index in order of nodes were inserted.
Thanks.
Upvotes: 1
Views: 954
Reputation: 35011
If you're trying to track insertion order, how about this?
public class MyTreeModel extends DefaultTreeModel {
int nodeNum = 0;
Map<MutableTreeNode,Integer> nodeOrder = ...;
public void insertNodeInto(MutableTreeNode newChild, MutableTreeNode parent, int index) {
nodeOrder.put(newChild, nodeNum++);
super.insertNodeInto(newChild, parent, index);
}
}
Upvotes: 2