Java JTree get selected node

Description

Java JTree get selected node

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. j  a v a2s  . 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