next up previous
Next: Practical Programming of JTrees Up: Listening for tree actions Previous: Listening for tree selections

Listening for tree expansions

Events caused by the user expanding or collapsing a node can be intercepted in a tree object.

The ExpandTreeExample.java example:

The full code listing for ExpandTreeExample.java is as follows:

// Imports
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.tree.*;

class ExpandTreeExample
		extends 	JFrame
		implements	TreeExpansionListener
 {
	// Instance attributes used in this example
	private	JPanel		topPanel;
	private	JTree		tree;
	private	JScrollPane scrollPane;

	// Constructor of main frame
	public ExpandTreeExample()
	{
		// Set the frame characteristics
		setTitle( "TreeExpansionListener Application" );
		setSize( 300, 300 );
		setBackground( Color.gray );

		// Create a panel to hold all other components
		topPanel = new JPanel();
		topPanel.setLayout( new BorderLayout() );
		getContentPane().add( topPanel );

		// Create a new tree control
		tree = new JTree();

		// Add a selection listener
		tree.addTreeExpansionListener( this );

		// Add the listbox to a scrolling pane
		scrollPane = new JScrollPane();
		scrollPane.getViewport().add( tree );
		topPanel.add( scrollPane, BorderLayout.CENTER );
	}

	// Handle tree item expansion
	public void treeExpanded( TreeExpansionEvent event )
	{
		if( event.getSource() == tree )
		{
			// Display the full selection path
			TreePath path = event.getPath();
			System.out.println( "Node Expanded=" + path.toString() );
		}
	}

	// Handle tree item expansion
	public void treeCollapsed( TreeExpansionEvent event )
	{
		if( event.getSource() == tree )
		{
			// Display the full selection path
			TreePath path = event.getPath();
			System.out.println( "Node Collapsed=" + path.toString() );
		}
	}

	// Main entry point for this example
	public static void main( String args[] )
	{
		// Create an instance of the test application
		ExpandTreeExample mainFrame	= new ExpandTreeExample();
		mainFrame.setVisible( true );
	}
}



Dave Marshall
4/14/1999