Get child count, depth, leaf count : JTree Node « Swing « Java Tutorial






import javax.swing.JFrame;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;

public class MainClass extends JFrame {

  public MainClass() {
    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) {
    MainClass t = new MainClass();
  }
}








14.67.JTree Node
14.67.1.Get child count, depth, leaf count
14.67.2.Adding a Node to a JTree Component
14.67.3.Delete tree node
14.67.4.Removing a Node to a JTree Component
14.67.5.Expression TreeExpression Tree
14.67.6.Swing TreeSwing Tree
14.67.7.JTree node mouse click event
14.67.8.A JTree subclass that displays the tree of AWT or Swing component that make up a GUI
14.67.9.Tree with custom icon
14.67.10.CheckBox Tree node
14.67.11.Get path for all expanded or not expanded tree pathes
14.67.12.Converting All Nodes in a JTree Component to a TreePath Array
14.67.13.Expanding or Collapsing All Nodes in a JTree Component
14.67.14.JTree root cannot be removed with removeNodeFromParent(), use DefaultTreeModel.setRoot() to remove the root
14.67.15.Searching node in a JTree