Introduction to Java Programming-Comprehensive Version (6th Edition)

 

[Page 1085]

31.14. Tree Events

JTree can fire TreeSelectionEvent and TreeExpansionEvent , among many other events. Whenever a new node is selected, JTree fires a TreeSelectionEvent . Whenever a node is expanded or collapsed , JTree fires a TreeExpansionEvent . To handle the tree selection event, a listener must implement the TreeSelectionListener interface, which contains a single handler named valueChanged method. TreeExpansionListener contains two handlers named treeCollapsed and treeExpanded for handling node expansion or node closing.

The following code displays a selected node:

void valueChanged(TreeSelectionEvent e) { TreePath path = e.getNewLeadSelectionPath(); TreeNode treeNode = (TreeNode)path.getLastPathComponent(); System.out.println( "The selected node is " + treeNode.toString()); }

 

Категории