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.
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);
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.