implements TreeSelectionListener : TreeSelectionListener « Swing Event « Java Tutorial






import java.awt.BorderLayout;

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

public class Main extends JFrame {
  public Main() {
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    DefaultMutableTreeNode root = new DefaultMutableTreeNode("abcde");
    DefaultMutableTreeNode node = new DefaultMutableTreeNode("1");
    node.add(new DefaultMutableTreeNode("12345"));
    node.add(new DefaultMutableTreeNode("testing"));
    root.add(node);
    root.add(new DefaultMutableTreeNode("1234567890"));

    TreeModel tm = new DefaultTreeModel(root);
    JTree tree = new JTree(tm);
    tree.getSelectionModel().addTreeSelectionListener(new Selector());
    tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
    getContentPane().add(tree, BorderLayout.CENTER);
    pack();
    setVisible(true);
  }

  private class Selector implements TreeSelectionListener {
    public void valueChanged(TreeSelectionEvent event) {
      Object obj = event.getNewLeadSelectionPath().getLastPathComponent();
      System.out.println("" + obj.toString().length());
    }
  }

  public static void main(String[] args) {
    Main m = new Main();
  }
}








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