FileDocCategorySizeDatePackage
SampleTree.javaAPI DocSun JDK 1.4.2 Example21614Thu May 12 00:35:28 BST 2005None

SampleTree

public class SampleTree extends Object
A demo for illustrating how to do different things with JTree. The data that this displays is rather boring, that is each node will have 7 children that have random names based on the fonts. Each node is then drawn with that font and in a different color. While the data isn't interesting the example illustrates a number of things: For an example of dynamicaly loading children refer to DynamicTreeNode. For an example of adding/removing/inserting/reloading refer to the inner classes of this class, AddAction, RemovAction, InsertAction and ReloadAction. For an example of creating your own cell renderer refer to SampleTreeCellRenderer. For an example of subclassing JTreeModel for editing refer to SampleTreeModel.
version
1.22 01/23/03
author
Scott Violet

Fields Summary
protected JFrame
frame
Window for showing Tree.
protected JTree
tree
Tree used for the example.
protected DefaultTreeModel
treeModel
Tree model.
Constructors Summary
public SampleTree()
Constructs a new instance of SampleTree.

	// Force SampleTree to come up in the Cross Platform L&F
	try {
	    UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
	    // If you want the System L&F instead, comment out the above line and
	    // uncomment the following:
	    // UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
	} catch (Exception exc) {
	    System.err.println("Error loading L&F: " + exc);
	}


	JMenuBar         menuBar = constructMenuBar();
	JPanel           panel = new JPanel(true);

	frame = new JFrame("SampleTree");
	frame.getContentPane().add("Center", panel);
	frame.setJMenuBar(menuBar);
	frame.setBackground(Color.lightGray);

	/* Create the JTreeModel. */
	DefaultMutableTreeNode root = createNewNode("Root");
	treeModel = new SampleTreeModel(root);

	/* Create the tree. */
	tree = new JTree(treeModel);

	/* Enable tool tips for the tree, without this tool tips will not
	   be picked up. */
	ToolTipManager.sharedInstance().registerComponent(tree);

	/* Make the tree use an instance of SampleTreeCellRenderer for
	   drawing. */
	tree.setCellRenderer(new SampleTreeCellRenderer());

	/* Make tree ask for the height of each row. */
	tree.setRowHeight(-1);

	/* Put the Tree in a scroller. */
	JScrollPane        sp = new JScrollPane();
	sp.setPreferredSize(new Dimension(300, 300));
	sp.getViewport().add(tree);

	/* And show it. */
	panel.setLayout(new BorderLayout());
	panel.add("Center", sp);
	panel.add("South", constructOptionsPanel());

	frame.addWindowListener( new WindowAdapter() {
	    public void windowClosing(WindowEvent e) {System.exit(0);}});

	frame.pack();
	frame.show();
    
Methods Summary
private javax.swing.JMenuBarconstructMenuBar()
Construct a menu.

	JMenu            menu;
	JMenuBar         menuBar = new JMenuBar();
	JMenuItem        menuItem;

	/* Good ol exit. */
	menu = new JMenu("File");
	menuBar.add(menu);

	menuItem = menu.add(new JMenuItem("Exit"));
	menuItem.addActionListener(new ActionListener() {
	    public void actionPerformed(ActionEvent e) {
		System.exit(0);
	    }});

	/* Tree related stuff. */
	menu = new JMenu("Tree");
	menuBar.add(menu);

	menuItem = menu.add(new JMenuItem("Add"));
	menuItem.addActionListener(new AddAction());

	menuItem = menu.add(new JMenuItem("Insert"));
	menuItem.addActionListener(new InsertAction());

	menuItem = menu.add(new JMenuItem("Reload"));
	menuItem.addActionListener(new ReloadAction());

	menuItem = menu.add(new JMenuItem("Remove"));
	menuItem.addActionListener(new RemoveAction());

	return menuBar;
    
private javax.swing.JPanelconstructOptionsPanel()
Constructs a JPanel containing check boxes for the different options that tree supports.

	JCheckBox               aCheckbox;
	JPanel           retPanel = new JPanel(false);
	JPanel           borderPane = new JPanel(false);

	borderPane.setLayout(new BorderLayout());
	retPanel.setLayout(new FlowLayout());

	aCheckbox = new JCheckBox("show handles");
	aCheckbox.setSelected(tree.getShowsRootHandles());
	aCheckbox.addChangeListener(new ShowHandlesChangeListener());
	retPanel.add(aCheckbox);

	aCheckbox = new JCheckBox("show root");
	aCheckbox.setSelected(tree.isRootVisible());
	aCheckbox.addChangeListener(new ShowRootChangeListener());
	retPanel.add(aCheckbox);

	aCheckbox = new JCheckBox("editable");
	aCheckbox.setSelected(tree.isEditable());
	aCheckbox.addChangeListener(new TreeEditableChangeListener());
	aCheckbox.setToolTipText("Triple click to edit");
	retPanel.add(aCheckbox);

	borderPane.add(retPanel, BorderLayout.CENTER);

	/* Create a set of radio buttons that dictate what selection should
	   be allowed in the tree. */
	ButtonGroup           group = new ButtonGroup();
	JPanel         buttonPane = new JPanel(false);
	JRadioButton          button;

	buttonPane.setLayout(new FlowLayout());
	button = new JRadioButton("Single");
	button.addActionListener(new AbstractAction() {
	    public boolean isEnabled() { return true; }
	    public void actionPerformed(ActionEvent e) {
		tree.getSelectionModel().setSelectionMode
		    (TreeSelectionModel.SINGLE_TREE_SELECTION);
	    }
	});
	group.add(button);
	buttonPane.add(button);
	button = new JRadioButton("Contiguous");
	button.addActionListener(new AbstractAction() {
	    public boolean isEnabled() { return true; }
	    public void actionPerformed(ActionEvent e) {
		tree.getSelectionModel().setSelectionMode
		    (TreeSelectionModel.CONTIGUOUS_TREE_SELECTION);
	    }
	});
	group.add(button);
	buttonPane.add(button);
	button = new JRadioButton("Discontiguous");
	button.addActionListener(new AbstractAction() {
	    public boolean isEnabled() { return true; }
	    public void actionPerformed(ActionEvent e) {
		tree.getSelectionModel().setSelectionMode
		    (TreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION);
	    }
	});
	button.setSelected(true);
	group.add(button);
	buttonPane.add(button);

	borderPane.add(buttonPane, BorderLayout.SOUTH);

	// NOTE: This will be enabled in a future release.
	// Create a label and combobox to determine how many clicks are
	// needed to expand.
/*
	JPanel               clickPanel = new JPanel();
	Object[]             values = { "Never", new Integer(1),
					new Integer(2), new Integer(3) };
	final JComboBox      clickCBox = new JComboBox(values);

	clickPanel.setLayout(new FlowLayout());
	clickPanel.add(new JLabel("Click count to expand:"));
	clickCBox.setSelectedIndex(2);
	clickCBox.addActionListener(new ActionListener() {
	    public void actionPerformed(ActionEvent ae) {
		Object       selItem = clickCBox.getSelectedItem();

		if(selItem instanceof Integer)
		    tree.setToggleClickCount(((Integer)selItem).intValue());
		else // Don't toggle
		    tree.setToggleClickCount(0);
	    }
	});
	clickPanel.add(clickCBox);
	borderPane.add(clickPanel, BorderLayout.NORTH);
*/
	return borderPane;
    
protected javax.swing.tree.DefaultMutableTreeNodecreateNewNode(java.lang.String name)

	return new DynamicTreeNode(new SampleData(null, Color.black, name));
    
protected javax.swing.tree.DefaultMutableTreeNodegetSelectedNode()
Returns the TreeNode instance that is selected in the tree. If nothing is selected, null is returned.

	TreePath   selPath = tree.getSelectionPath();

	if(selPath != null)
	    return (DefaultMutableTreeNode)selPath.getLastPathComponent();
	return null;
    
protected javax.swing.tree.TreePath[]getSelectedPaths()
Returns the selected TreePaths in the tree, may return null if nothing is selected.

        return tree.getSelectionPaths();
    
public static voidmain(java.lang.String[] args)

	new SampleTree();