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);
}
}
}
|