O'Reilly logo

Java Swing, 2nd Edition by Brian Cole, James Elliott, Marc Loy, Robert Eckstein, Dave Wood

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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), ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required