【问题标题】:Java: preorderEnumeration in TreeModel, how to get depthindex and sibling index?Java:TreeModel中的preorderEnumeration,如何获取深度索引和兄弟索引?
【发布时间】:2012-03-04 21:03:49
【问题描述】:
    for (Enumeration e = root.preorderEnumeration(); e.hasMoreElements() && theNode == null;) {
        DefaultMutableTreeNode node = (DefaultMutableTreeNode) e.nextElement();

    }

对于上面的那个例子,你怎么知道你在树枝里有多深?如果你正在迭代兄弟姐妹,你如何获得它的索引?

【问题讨论】:

    标签: java swing jtree treemodel


    【解决方案1】:

    您可以通过计算从node 迭代getParent() 直到结果为null 的父级数量来获得深度。

    感谢node.getIndex(node.getParent()),您可以获得node的索引。

    如果您遍历的每个节点都需要这两种信息,我建议您编写自己的遍历器代码以提高效率,灵感来自DefaultMutableTreeNode.getNextNode()DefaultMutableTreeNode.PreorderEnumeration 内部类。在后一种情况下,生成的堆栈应该包含一个结构{ node, treeDepth, siblingIndex }

    【讨论】:

    • 不要重新发明轮子,有 api 用于获取节点与根的距离: node.getLevel() 直到最近才意识到这一点,略读 api 文档会产生奇迹:- )
    • 我同意。 getLevel() 完全按照我的描述进行计数,但如果您需要每个节点的信息,则效率不高。
    猜你喜欢
    • 2012-10-09
    • 2017-11-19
    • 1970-01-01
    • 1970-01-01
    • 2021-12-31
    • 2018-12-23
    • 1970-01-01
    • 1970-01-01
    • 2016-09-17
    相关资源
    最近更新 更多