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()); }