Java JTree handle tree selection event

Description

Java JTree handle tree selection event

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreeSelectionModel;

public class Main {

  public static void main(String[] a) {
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    DefaultMutableTreeNode root = new DefaultMutableTreeNode("Root");
    root.add(new DefaultMutableTreeNode("A"));
    root.add(new DefaultMutableTreeNode("B"));
    root.add(new DefaultMutableTreeNode("C"));
    JTree tree = new JTree(root);
    // w w  w  . ja v a2 s. c  o  m
    tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
    tree.addTreeSelectionListener(new SelectionListener());

    frame.add(new JScrollPane(tree));

    frame.setSize(300, 200);
    frame.setVisible(true);
  }

}

class SelectionListener implements TreeSelectionListener {

  public void valueChanged(TreeSelectionEvent se) {
    JTree tree = (JTree) se.getSource();
    DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) tree
        .getLastSelectedPathComponent();
    String selectedNodeName = selectedNode.toString();
    if (selectedNode.isLeaf()) {

      System.out.println(selectedNodeName);

    }
  }
}



PreviousNext

Related