【问题标题】:How can I count the number of nodes in a JTree?如何计算 JTree 中的节点数?
【发布时间】:2012-12-19 14:17:30
【问题描述】:

我正在使用JIDE's CheckBoxTree 来显示一个嵌套的复选框树,如下例所示:

我想知道树模型包含多少个节点。

如果我调用 tree.getModel().getChildCount(rootNode) 方法,我只会得到直接子节点的数量(例如,在这种情况下为 12 个),而不是进一步嵌套的任何子节点的数量(20+)。

【问题讨论】:

  • 遍历模型并计数 :-) 如果节点是 DefaultMutableTreeNode 类型,则有 api 执行此操作。如果您(有机会 :) 使用 SwingX,它具有遍历任意模型的实用方法。否则,看代码自己实现。
  • 你必须递归地检查和计算所有节点。这样,您也可以根据需要忽略文件夹节点

标签: java swing tree jtree


【解决方案1】:

递归:

public int getNumberOfNodes(TreeModel model)  
{  
    return getNumberOfNodes(model, model.getRoot());  
}  

private int getNumberOfNodes(TreeModel model, Object node)  
{  
    int count = 1;
    int nChildren = model.getChildcount(node);  
    for (int i = 0; i < nChildren; i++)  
    {  
        count += getNumberOfNodes(model, model.getChild(node, i));  
    }  
    return count;  
}

【讨论】:

  • getChildcount 应该是 getChildCount('Count' 的大写'c')
【解决方案2】:

使用getChild() 方法自己遍历树。

http://en.wikipedia.org/wiki/Tree_traversal

【讨论】:

  • 我发现要获得准确的计数特别困难,因为有孩子的节点被计算了两次。
猜你喜欢
  • 2011-04-15
  • 1970-01-01
  • 1970-01-01
  • 2011-08-06
  • 2020-12-21
  • 2012-07-13
  • 2012-05-13
  • 1970-01-01
  • 2014-07-31
相关资源
最近更新 更多