我有一个用重复条目填充的列表。我使用散列来存储此列表中的每个唯一条目。然后,每个键将指向一个表示JTree节点的DefaultMutableTreeNode类型的对象。我的目标是让这个节点指向列表中具有相同节点的所有条目-与父节点相同。
我已经没有问题地添加了这些父节点,但是当添加子节点时(通过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();
}
}发布于 2012-08-02 17:59:35
你在这里弄错了
// 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());https://stackoverflow.com/questions/9069024
复制相似问题