// Copyright MageLang Institute; Version $Id: //depot/main/src/edu/modules/Swing/magercises/TreeExample/Solution/TreeExample.java#2 $ /* * Demonstrates tree view stuff in a scrollable pane. */ import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.event.*; import javax.swing.tree.*; public class TreeExample extends JFrame { // The initial width and height of the frame static int WIDTH = 300; static int HEIGHT = 200; public TreeExample(String lab) { super(lab); // Create the tree nodes DefaultMutableTreeNode component = new DefaultMutableTreeNode("Component"); DefaultMutableTreeNode container = new DefaultMutableTreeNode("Container"); DefaultMutableTreeNode box = new DefaultMutableTreeNode("Box"); DefaultMutableTreeNode jComponent = new DefaultMutableTreeNode("JComponent"); DefaultMutableTreeNode abstractButton = new DefaultMutableTreeNode("AbstractButton"); DefaultMutableTreeNode jButton = new DefaultMutableTreeNode("JButton"); DefaultMutableTreeNode jMenuItem = new DefaultMutableTreeNode("JMenuItem"); DefaultMutableTreeNode jToggle = new DefaultMutableTreeNode("JToggleButton"); DefaultMutableTreeNode jLabel = new DefaultMutableTreeNode("JLabel"); DefaultMutableTreeNode etc = new DefaultMutableTreeNode("..."); // Group the nodes component.add(container); container.add(box); container.add(jComponent); jComponent.add(abstractButton); abstractButton.add(jButton); abstractButton.add(jMenuItem); abstractButton.add(jToggle); jComponent.add(jLabel); jComponent.add(etc); // Create the TreeSelectionListener TreeSelectionListener listener = new MyTreeSelectionListener(); TreePanel tp = new TreePanel(component, listener); Container content = getContentPane(); content.add(tp, BorderLayout.CENTER); } public static void main(String args[]) { TreeExample frame = new TreeExample("Tree Example"); frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) {System.exit(0);} }); frame.setSize(WIDTH, HEIGHT); frame.setVisible(true); } class MyTreeSelectionListener implements TreeSelectionListener { public void valueChanged (TreeSelectionEvent event) { TreePath path = event.getPath(); System.out.println ("Selected: " + path.getLastPathComponent()); Object elements[] = path.getPath(); for (int i=0; i" + elements[i]); } System.out.println (); } } }