Listening for Selection Events in a JTree Component

This example adds a listener for selection events to a tree component.
tree.addTreeSelectionListener(new TreeSelectionListener() {
    public void valueChanged(TreeSelectionEvent evt) {
        // Get all nodes whose selection status has changed
        TreePath[] paths = evt.getPaths();

        // Iterate through all affected nodes
        for (int i=0; i<paths.length; i++) {
            if (evt.isAddedPath(i)) {
                // This node has been selected
            } else {
                // This node has been deselected
            }
        }
    }
});

Post a comment

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Image CAPTCHA
Enter the characters shown in the image. Ignore spaces and be careful about upper and lower case.