Share the post "Get Total Count Of Leaf Nodes From A Node In JTree"
To get a JTree node’s total number of leaf nodes, you have to make use of the DefaultMutableTreeNode because it already has a method for counting all the leaf nodes from a starting node. Once you can get the TreePath object of the JTree, you can then convert the TreePath‘s getLastPathComponent() and cast it to a DefaultMutableTreeNode object.
Then you can call the getLeafCount() method of that DefaultMutableTreeNode object. Simple right? Yeah, if you manage to find it out early. I kept focusing on the TreeNode object which took me a long time to find out regarding the DefaultMutableTreeNode class. Here is the method.
|
1 2 3 4 5 6 7 8 |
public static int getLeafCount(TreePath path) { int count = 0; if (path != null) { DefaultMutableTreeNode dmtn = (DefaultMutableTreeNode) path.getLastPathComponent(); count = dmtn.getLeafCount(); } return count; } |