Java by API/javax.swing.event/TreeSelectionListener

Материал из Java эксперт
Версия от 14:33, 31 мая 2010; Admin (обсуждение | вклад) (1 версия)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

implements TreeSelectionListener

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());
      }
    }
  }
}