package com.demo;
import java.awt.Component;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JTree;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeCellRenderer;
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.getUserObject() instanceof Category) {
Category category = (Category) selectedNode.getUserObject();
System.out.println(category.toString());
}
}
});
List<Category> categories = new ArrayList<Category>();
categories.add(new Category(1, "Category 1"));
categories.add(new Category(2, "Category 2"));
categories.add(new Category(3, "Category 3"));
categories.add(new Category(4, "Category 4"));
DefaultMutableTreeNode root = new DefaultMutableTreeNode("Categories");
for (Category category : categories) {
DefaultMutableTreeNode node = new DefaultMutableTreeNode(category);
root.add(node);
}
DefaultTreeModel defaultTreeModel = new DefaultTreeModel(root);
jtreeCategory.setModel(defaultTreeModel);
jtreeCategory.setCellRenderer(new CategoryTreeCellRenderer());
}
public static class CategoryTreeCellRenderer extends DefaultTreeCellRenderer {
@Override
public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded,
boolean leaf, int row, boolean hasFocus) {
Component component = super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus);
DefaultMutableTreeNode node = (DefaultMutableTreeNode) value;
if (node.getUserObject() instanceof Category) {
Category category = (Category) node.getUserObject();
this.setText(category.getName());
}
return component;
}
}
public static class Category {
private int id;
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Category(int id, String name) {
super();
this.id = id;
this.name = name;
}
public Category() {
super();
}
@Override
public String toString() {
return "Category [id=" + id + ", name=" + name + "]";
}
}
}