Search code examples
javajtreedom4j

Java: getRowForLocation() returns different row int when Jtree has expanded nodes or collapsed nodes


JTree jtree has a mouse listener attached to it.when the user clicks on a Jtree component node, I get it's row integer via

 jtree.getRowForLocation(evt.getX(), evt.getY());

the problem is that the return row integer is different when there are jtree nodes which are expanded and when it's collapsed.

I need a way to somehow get a unique and absolute ID of each jtree nodes clicked so that there is no confusions.

Is there a way to add data to the Jtree component?

Otherwise, I need a way to listen to when nodes are expanded and recalculate the row returned from that above function....


Solution

  • In your current approach you are relying on the state of the tree view to identify the node. However, as you have found out the state of the view can change. What does not change is the tree model that is underlying the view.

    If you need a unique ID for each node then you should add this directly to each tree node in your tree model. In the mouse listener you can then detect the node that you clicked on and access its unique ID.