01: package examples.swingdemos;
02:
03: /*
04: * This code is based on an example provided by Richard Stanford,
05: * a tutorial reader.
06: */
07:
08: import java.awt.*;
09: import java.awt.event.*;
10:
11: import javax.swing.*;
12: import javax.swing.tree.*;
13:
14: public class DynamicTreeDemo extends JPanel {
15: protected int newNodeSuffix = 1;
16:
17: public DynamicTreeDemo() {
18: //create the components
19: final DynamicTree treePanel = new DynamicTree();
20: populateTree(treePanel);
21:
22: JButton addButton = new JButton("Add");
23: addButton.addActionListener(new ActionListener() {
24: public void actionPerformed(ActionEvent e) {
25: treePanel.addObject("New Node " + newNodeSuffix++);
26: }
27: });
28:
29: JButton removeButton = new JButton("Remove");
30: removeButton.addActionListener(new ActionListener() {
31: public void actionPerformed(ActionEvent e) {
32: treePanel.removeCurrentNode();
33: }
34: });
35:
36: JButton clearButton = new JButton("Clear");
37: clearButton.addActionListener(new ActionListener() {
38: public void actionPerformed(ActionEvent e) {
39: treePanel.clear();
40: }
41: });
42:
43: //Lay everything out.
44: setLayout(new BorderLayout());
45: treePanel.setPreferredSize(new Dimension(300, 150));
46: add(treePanel, BorderLayout.CENTER);
47:
48: JPanel panel = new JPanel();
49: panel.setLayout(new GridLayout(0, 1));
50: panel.add(addButton);
51: panel.add(removeButton);
52: panel.add(clearButton);
53: add(panel, BorderLayout.EAST);
54: }
55:
56: public void populateTree(DynamicTree treePanel) {
57: String p1Name = new String("Parent 1");
58: String p2Name = new String("Parent 2");
59: String c1Name = new String("Child 1");
60: String c2Name = new String("Child 2");
61:
62: DefaultMutableTreeNode p1, p2;
63:
64: p1 = treePanel.addObject(null, p1Name);
65: p2 = treePanel.addObject(null, p2Name);
66:
67: treePanel.addObject(p1, c1Name);
68: treePanel.addObject(p1, c2Name);
69:
70: treePanel.addObject(p2, c1Name);
71: treePanel.addObject(p2, c2Name);
72: }
73:
74: public static void main(String[] args) {
75: JFrame frame = new JFrame("DynamicTreeDemo");
76:
77: Container contentPane = frame.getContentPane();
78: contentPane.setLayout(new GridLayout(1, 1));
79: contentPane.add(new DynamicTreeDemo());
80:
81: frame.addWindowListener(new WindowAdapter() {
82: public void windowClosing(WindowEvent e) {
83: System.exit(0);
84: }
85: });
86:
87: frame.pack();
88: frame.setVisible(true);
89: }
90: }
|