我有一个填充了重复条目的列表。我正在使用散列来存储此列表中的每个唯一条目。然后每个键将指向一个 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/