DefaultMutableTreeNode: breadthFirstEnumeration() : DefaultMutableTreeNode « javax.swing.tree « Java by API






DefaultMutableTreeNode: breadthFirstEnumeration()

import java.awt.BorderLayout;
import java.util.Enumeration;

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreeModel;
import javax.swing.tree.TreeNode;
import javax.swing.tree.TreePath;

public class MainClass {
  public static void main(String args[]) {
    JFrame frame = new JFrame("Traverse Tree");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JTree tree = new JTree();
    tree.setRootVisible(true);
    TreeModel model = tree.getModel();
    Object rootObject = model.getRoot();
    if ((rootObject != null) && (rootObject instanceof DefaultMutableTreeNode)) {
      DefaultMutableTreeNode r = (DefaultMutableTreeNode) rootObject;
      printDescendents(r);
      Enumeration breadth = r.breadthFirstEnumeration();
      Enumeration depth = r.depthFirstEnumeration();
      Enumeration preOrder = r.preorderEnumeration();
      printEnumeration(breadth, "Breadth");
      printEnumeration(depth, "Depth");
      printEnumeration(preOrder, "Pre");
    }

    TreeSelectionListener treeSelectionListener = new TreeSelectionListener() {
      public void valueChanged(TreeSelectionEvent treeSelectionEvent) {
        JTree treeSource = (JTree) treeSelectionEvent.getSource();
        TreePath path = treeSource.getSelectionPath();
        System.out.println(path);
        System.out.println(path.getPath());
        System.out.println(path.getParentPath());
        System.out.println(((DefaultMutableTreeNode) path.getLastPathComponent()).getUserObject());
        System.out.println(path.getPathCount());
      }
    };
    tree.addTreeSelectionListener(treeSelectionListener);

    JScrollPane scrollPane = new JScrollPane(tree);
    frame.add(scrollPane, BorderLayout.CENTER);
    frame.setSize(300, 400);
    frame.setVisible(true);
  }

  private static void printEnumeration(Enumeration e, String label) {
    System.out.println("-----" + label + "-----");
    while (e.hasMoreElements()) {
      System.out.println(e.nextElement());
    }
  }

  public static void printDescendents(TreeNode root) {
    System.out.println(root);
    Enumeration children = root.children();
    if (children != null) {
      while (children.hasMoreElements()) {
        printDescendents((TreeNode) children.nextElement());
      }
    }
  }
}

           
       








Related examples in the same category

1.new DefaultMutableTreeNode(String text)
2.DefaultMutableTreeNode: add(MutableTreeNode newChild)
3.DefaultMutableTreeNode: depthFirstEnumeration()
4.DefaultMutableTreeNode: getUserObject()
5.DefaultMutableTreeNode: preorderEnumeration()
6.DefaultMutableTreeNode: setToolTipText(String text)