package uiintro;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.tree.*;            // note -- had to add more packages
import javax.swing.event.*;           // trees (and their events) came after awt

public class TreeDemo extends JFrame {

  private JTree tree;
  private JLabel label;

  public TreeDemo() {
    this.setSize(200, 300);
    tree = new JTree(generateTreeModel());
    this.getContentPane().add(tree, BorderLayout.CENTER);
    label = new JLabel("Selection path: none");
    this.getContentPane().add(label, BorderLayout.SOUTH);

    // add a listener that updates what's selected. why is it getNew*Lead*SelectionPath?
    // technically, there are two parts of a selection -- the anchor (that is, the first
    // element selected, and the lead (the last -- think of it as being the "leading"
    // element as you sweep through a selection).
    //
    tree.addTreeSelectionListener(new TreeSelectionListener() {
      public void valueChanged(TreeSelectionEvent tse) {
        TreePath path = tse.getNewLeadSelectionPath();
        label.setText("Selected: " + path.getLastPathComponent());
      }
    });

    this.setVisible(true);
  }

  TreeModel generateTreeModel() {
    DefaultTreeModel treeModel;

    DefaultMutableTreeNode root = new DefaultMutableTreeNode("Root");
    DefaultMutableTreeNode subroot = new DefaultMutableTreeNode("Subroot");
    DefaultMutableTreeNode leaf1 = new DefaultMutableTreeNode("Leaf 1");
    DefaultMutableTreeNode leaf2 = new DefaultMutableTreeNode("Leaf 2");

    treeModel = new DefaultTreeModel(root);
    treeModel.insertNodeInto(subroot, root, 0);
    treeModel.insertNodeInto(leaf1, subroot, 0);
    treeModel.insertNodeInto(leaf2, root, 1);

    return treeModel;
  }
}