swing - JTree 动态节点插入

标签 swing 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();
    }
}

最佳答案

你在这里犯错

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

关于swing - JTree 动态节点插入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9069024/

相关文章:

java - 是否可以使用 jtextfield 和 Jlist 进行自动完成?

java - 是否可以自定义 JTree 节点?

java - 获取 JTree 上单击节点的基础节点数据?

java - 如何使用自定义模型更新树节点大小?

java - 在java swing中查找下一个出现的树节点

java - 可以有多个顶级 TreeNode 吗?

java - Swing - 多个 GUI

java - 如何创建一个平铺 map (我只是得到一个白屏)

java - 到处都找不到符号错误

java - GridLayout 单元格真的都是相同大小吗?