How to Write a Tree Model Listener
By implementing a tree model listener, you can detect when the data displayed by a tree changes. You might use a tree model listener to detect when the user edits tree nodes. To see an example and a discussion, read Dynamically Changing a Tree (page 447) in Chapter 7.
The Tree Model Listener API
Table 37 lists the methods in the TreeModelListener interface and Table 38 describes the methods in the TreeModelEvent class. Note that TreeModelListener has no adapter class. Also refer to the TreeModelListener API documentation at: http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/event/TreeModelListener.html. The TreeModelEvent API documentation is online at: http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/event/TreeModelEvent.html.
Table 37. The TreeModelListener Interface|
treeNodesChanged(TreeModelEvent) | Called when one or more sibling nodes have changed in some way. | treeNodesInserted(TreeModelEvent) | Called after nodes have been inserted into the tree. | treeNodesRemoved(TreeModelEvent) | Called after nodes have been removed from the tree. | treeStructureChanged(TreeModelEvent) | Called after the tree's structure has drastically changed. |
Table 38. The TreeModelEvent API|
Object getSource()
(in java.util.EventObject)
| Return the object that fired the event. | int[] getChildIndices() | For treeNodesChanged, treeNodesInserted, and treeNodesRemoved, return the indices of the changed, inserted, or deleted nodes, respectively. Return nothing useful for treeStructureChanged. | Object[] getChildren() | Return the objects corresponding to the child indices. | Object[] getPath() | Return the path to the parent of the changed, inserted, or deleted nodes. For treeStructureChanged, return the path to the node beneath which the structure has changed. | TreePath getTreePath() | Return the same thing as getPath, but as a TreePath object. |
Examples That Use Tree Model Listeners
The following examples use tree model listeners.
|
DynamicTreeDemo | How to Use Trees (page 437) | Implements a tree model listener to detect when the user has edited a node's data. |
|