Get child count, depth, leaf count for JTree node in Java
Description
The following code shows how to get child count, depth, leaf count for JTree node.
Example
/*from w w w . jav a 2s . com*/
import javax.swing.JFrame;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
public class Main extends JFrame {
public Main() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
DefaultMutableTreeNode root = new DefaultMutableTreeNode("+");
root.add(new DefaultMutableTreeNode(new Integer(3)));
DefaultMutableTreeNode node = new DefaultMutableTreeNode("*");
node.add(new DefaultMutableTreeNode(new Integer(4)));
node.add(new DefaultMutableTreeNode(new Integer(5)));
root.add(node);
JTree tree = new JTree(root);
getContentPane().add(tree);
pack();
setVisible(true);
System.out.println("The root has " + root.getChildCount() + " children");
System.out.println("The tree's depth is " + root.getDepth());
System.out.println("The tree has " + root.getLeafCount() + " leaves");
System.out.println("'Root' is really a root? " + root.isRoot());
System.out.println("Root's userObject: " + root.toString());
}
public static void main(String[] args) {
Main t = new Main();
}
}
The code above generates the following result.
Home »
Java Tutorial »
Swing »
Java Tutorial »
Swing »