首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >JTree动态节点插入

JTree动态节点插入
EN

Stack Overflow用户
提问于 2012-01-31 02:42:54
回答 1查看 1K关注 0票数 4

我有一个用重复条目填充的列表。我使用散列来存储此列表中的每个唯一条目。然后,每个键将指向一个表示JTree节点的DefaultMutableTreeNode类型的对象。我的目标是让这个节点指向列表中具有相同节点的所有条目-与父节点相同。

我已经没有问题地添加了这些父节点,但是当添加子节点时(通过insertNodeInto),只有父节点出现。下面是一个代码片段;我非常感谢您的建议/时间。

代码语言:javascript
复制
// 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();
    }
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-08-02 17:59:35

你在这里弄错了

代码语言:javascript
复制
// insert node to tree, relead model        
((DefaultMutableTreeNode)(root)).insert(
   new DefaultMutableTreeNode("parent node"), 
   root.getChildCount());

您已经在上面创建了节点parent,但不要使用它。在树中插入另一个节点,但仍在parent中插入子节点。这就是为什么它们不会出现在树上。

这段代码看起来像这样

代码语言:javascript
复制
// insert node to tree, relead model        
((DefaultMutableTreeNode)(root)).insert(
   parent, 
   root.getChildCount());
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/9069024

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档