How do I add selection listener to JTree?

This example shows you how to use the TreeSelectionListener to add a tree selection listener to the JTree component. In the listener method below you can see how to get the selected path and print out the selected path to the console.

package org.kodejava.swing;

import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreePath;
import java.awt.*;

public class JTreeSelectionListenerDemo extends JFrame {

    public JTreeSelectionListenerDemo() throws HeadlessException {
        initializeUI();
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(
                () -> new JTreeSelectionListenerDemo().setVisible(true));
    }

    private void initializeUI() {
        setSize(500, 500);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

        DefaultMutableTreeNode root = new DefaultMutableTreeNode("Root");
        DefaultMutableTreeNode chapterOne = new DefaultMutableTreeNode("Chapter One");
        DefaultMutableTreeNode one = new DefaultMutableTreeNode("1.1");
        DefaultMutableTreeNode two = new DefaultMutableTreeNode("1.2");
        DefaultMutableTreeNode three = new DefaultMutableTreeNode("1.3");

        root.add(chapterOne);
        chapterOne.add(one);
        chapterOne.add(two);
        chapterOne.add(three);

        JTree tree = new JTree(root);
        tree.addTreeSelectionListener(e -> {
            TreePath path = e.getPath();
            int pathCount = path.getPathCount();

            for (int i = 0; i < pathCount; i++) {
                System.out.print(path.getPathComponent(i).toString());
                if (i + 1 != pathCount) {
                    System.out.print(" | ");
                }
            }
            System.out.println();
        });

        JScrollPane pane = new JScrollPane(tree);
        pane.setPreferredSize(new Dimension(200, 400));

        getContentPane().add(pane);
    }
}
Wayan

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.