2012-01-30 102 views
4

我有一個填充了重複條目的列表。我正在使用散列來存儲此列表中的每個唯一條目。每個鍵然後將指向代表JTree節點的DefaultMutableTreeNode類型的對象。我的目標是讓該節點指向列表中與父節點具有相同節點的所有條目。JTree動態節點插入

我已經添加這些父節點沒有問題,但是當添加子節點(通過insertNodeInto)時,只有父節點出現。代碼片段在下面;我非常感謝建議/時間。

// an unsorted list of items 
List<MyObject>list = hash.get(key); 

// clause to check for size 
if (list.size() > 0) { 

    // iterate through each item in the list and fetch obj 
    for (int i=0; i < list.size(); i++) { 
     MyObject be = list.get(i); 

     // if object is not in hash, add to hash and point obj to new node 
     if (!hashParents.containsKey(be)) { 
       DefaultMutableTreeNode parent = 
        new DefaultMutableTreeNode(be.getSequence()); 

       // add the key and jtree node to hash 
       hashParents.put(be, parent);  

       // insert node to tree, relead model   
       ((DefaultMutableTreeNode)(root)).insert(
        new DefaultMutableTreeNode("parent node"), 
        root.getChildCount()); 
        ((DefaultTreeModel)(tree.getModel())).reload(); 
     } 

     // now that a parent-node exists, create a child 
     DefaultMutableTreeNode child = new DefaultMutableTreeNode("child"); 

     // insert the new child to the parent (from the hash) 
     ((DefaultTreeModel)(tree.getModel())).insertNodeInto(child, hashParents.get(be), 
      hashParents.get(be).getChildCount()); 

     // render the tree visible   
     ((DefaultTreeModel)(tree.getModel())).reload(); 
    } 
} 
+0

什麼問題的通知(在片段上方我會懷疑平原香草root.insert這不是後跟一個nodeWasInserted)。此外,重新加載不應該是必要的 - 一旦通知被修復:-) – kleopatra 2012-01-31 10:50:02

回答

0

您在此處

// insert node to tree, relead model   
((DefaultMutableTreeNode)(root)).insert(
    new DefaultMutableTreeNode("parent node"), 
    root.getChildCount()); 

錯誤您已經創建節點parent以上,但不使用它。您在樹中插入另一個節點,但您仍然在parent中插入子節點。這就是爲什麼他們不出現在樹中。

這段代碼的樣子

// insert node to tree, relead model   
((DefaultMutableTreeNode)(root)).insert(
    parent, 
    root.getChildCount());