Search code examples
javaswingtreejtree

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:

example image

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 (e.g. 12 in this case), and NOT the number of any children nested further (20+).


Solution

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