package com.demo;
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.TreeSelectionModel;
public class JFrameDemo {
public static void main(String[] args) {
JTree jtreeCategory = new JTree();
jtreeCategory.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
jtreeCategory.addTreeSelectionListener(new TreeSelectionListener() {
public void valueChanged(TreeSelectionEvent e) {
DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) jtreeCategory.getSelectionPath()
.getLastPathComponent();
if (selectedNode.isLeaf()) {
String category = selectedNode.getUserObject().toString();
System.out.println(category);
}
}
});
// Root Node
DefaultMutableTreeNode root = new DefaultMutableTreeNode("Categories");
// Category 1 Node
DefaultMutableTreeNode category1 = new DefaultMutableTreeNode("Category 1");
root.add(category1);
// Category 2 Node
DefaultMutableTreeNode category2 = new DefaultMutableTreeNode("Category 2");
root.add(category2);
// Category 3 Node
DefaultMutableTreeNode category3 = new DefaultMutableTreeNode("Category 3");
DefaultMutableTreeNode category3_1 = new DefaultMutableTreeNode("Category 3.1");
category3.add(category3_1);
DefaultMutableTreeNode category3_2 = new DefaultMutableTreeNode("Category 3.2");
category3.add(category3_2);
root.add(category3);
DefaultTreeModel defaultTreeModel = new DefaultTreeModel(root);
jtreeCategory.setModel(defaultTreeModel);
}
}