Tree Events

Trees generate three types of events worth mentioning. Apart from the obvious selection events (TreeSelectionEvent, TreeSelectionListener), you can receive expansion events (TreeExpansionEvent, TreeExpansionListener, TreeWillExpandListener) from the graphical side, and you can catch structural changes to the model itself (TreeModelEvent, TreeModelListener).

Figure 17-9 shows a simple program that uses the Every Event Listener (EEL) class (described in Chapter 3) to display all events that come from selecting, expanding, and editing a tree. (We use a tree built by the default JTree constructor.) For editing, you can change the text of a node or add and remove nodes so that you can monitor model events.

The JTree events as reported by our EEL utility

Figure 17-9. The JTree events as reported by our EEL utility

Here’s the source code required to hook up all the various events:

// TreeEvents.java // import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.event.*; import javax.swing.tree.*; public class TreeEvents extends JFrame implements TreeSelectionListener { JButton addB, deleteB; JTree tree; DefaultMutableTreeNode leadSelection; public TreeEvents( ) { super("Tree Event Demo"); setSize(300,200); setDefaultCloseOperation(EXIT_ON_CLOSE); EEL eel = EEL.getInstance( ); eel.addGui( ); tree = new JTree( ); tree.setExpandsSelectedPaths(true); tree.setEditable(true); getContentPane( ).add(new JScrollPane(tree), ...

Get Java Swing, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.