Sunday, January 8, 2012

How to Write a Tree Selection Listener

To detect when the user selects a node in a tree, you need to register a tree selection listener. Here is an example, taken from the TreeDemo example discussed in Responding to Node Selection, of detecting node selection in a tree that can have at most one node selected at a time:

tree.addTreeSelectionListener(new TreeSelectionListener() {
public void valueChanged(TreeSelectionEvent e) {
DefaultMutableTreeNode node = (DefaultMutableTreeNode)
tree.getLastSelectedPathComponent();

/* if nothing is selected */
if (node == null) return;

/* retrieve the node that was selected */
Object nodeInfo = node.getUserObject();
...
/* React to the node selection. */
...
}
});

To specify that the tree should support single selection, the program uses this code:

tree.getSelectionModel().setSelectionMode
(TreeSelectionModel.SINGLE_TREE_SELECTION);

The TreeSelectionModel interface defines three values for the selection mode:

DISCONTIGUOUS_TREE_SELECTION
This is the default mode for the default tree selection model. With this mode, any combination of nodes can be selected.
SINGLE_TREE_SELECTION
This is the mode used by the preceding example. At most one node can be selected at a time.
CONTIGUOUS_TREE_SELECTION
With this mode, only nodes in adjoining rows can be selected.
Running Codes

0 comments:

Post a Comment

Tu comentario será moderado la primera vez que lo hagas al igual que si incluyes enlaces. A partir de ahi no ser necesario si usas los mismos datos y mantienes la cordura. No se publicarán insultos, difamaciones o faltas de respeto hacia los lectores y comentaristas de este blog.