简体   繁体   English

如何计算JTree中的节点数?

[英]How can I count the number of nodes in a JTree?

I am using JIDE's CheckBoxTree to display a nested tree of checkboxes, as in this example: 我正在使用JIDE的CheckBoxTree来显示一个嵌套的复选框树,如下例所示:

示例图片

I would like to know how many nodes the tree model contains. 我想知道树模型包含多少个节点。

If I call the method tree.getModel().getChildCount(rootNode) , I only get the number of direct children (eg 12 in this case), and NOT the number of any children nested further (20+). 如果我调用方法tree.getModel()。getChildCount(rootNode) ,我只获得直接子节点的数量(例如在这种情况下为12),而不是进一步嵌套的任何子节点的数量(20+)。

Recursively: 递归:

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;  
}

Traverse the tree yourself using the getChild() method. 使用getChild()方法自己遍历树。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM