JTree动态节点插入

4
我有一个包含重复条目的列表。我正在使用哈希表来存储此列表中每个唯一条目。每个键都将指向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();
    }
}

你的通知有问题(在上面的片段中,我怀疑是未跟随节点插入的普通根插入)。此外,重新加载不应该是必要的 - 一旦通知被修复 :-) - kleopatra
1个回答

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接