How to Write a Tree Selection Listener : TreeSelectionListener « Swing Event « Java Tutorial






How to Write a Tree Selection Listener
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 UsingTreeSelectionListener {

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

    JTree tree = new JTree();
    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);

    }
  }
}








15.38.TreeSelectionListener
15.38.1.How to Write a Tree Selection ListenerHow to Write a Tree Selection Listener
15.38.2.Add nodes to a tree with tree node selection listener
15.38.3.TreeSelectionEvent.getNewLeadSelectionPath().getLastPathComponent()
15.38.4.implements TreeSelectionListener
15.38.5.TreeSelectionListener and TreeSelectionEvent