1
votes

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:

enter image description here

If I select one node, like picture after, the getSelectionRows return number 4.

enter image description here

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.

enter image description here

1

1 Answers

2
votes

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);
  } 
}