2014-10-29 63 views
1

我實現了一個JTree,我需要獲取選定節點的索引。以插入的順序獲取選定的JTree節點索引

我試着用這個代碼來獲取指數:

tree.addMouseListener(new MouseAdapter() { 
     @Override 
     public void mouseClicked(MouseEvent e) { 

      // This code to get selected index of node 
      int[] selectionRows = tree.getSelectionRows(); 
     } 
    }); 

但方法getSelectionRows返回取決於如果一些節點被collpased或擴展型動物的結果。例如:

這是我的樹:

enter image description here

如果我選擇一個節點,就像照片後,getSelectionRows返回數字4

enter image description here

但是,如果某個節點被摺疊後,像圖片之後,getSelectionRows返回3.

我需要thats alwa ys返回4,那就是索引的數量按照節點的順序被插入。

謝謝。

enter image description here

回答

2

如果你想跟蹤插入順序,這個怎麼樣?

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

感謝您的幫助,如何使用此映射獲取選定的節點索引? – computered 2014-10-29 18:17:52

+0

如果你有選定的節點,你可以做「int index = nodeOrder.get(selectedNode);」 – ControlAltDel 2014-10-29 18:26:27

+0

而這個變量selectedNode,我在哪裏得到的價值? – computered 2014-10-29 18:33:13