先创建User类的属性
package TreeMap; import javax.swing.*; import javax.swing.event.TreeSelectionEvent; import javax.swing.event.TreeSelectionListener; import javax.swing.tree.DefaultMutableTreeNode; /** * Created by Mr.Yx on 2017/4/19. */ class User { private String name; public User(String name) { this.name = name; } @Override public String toString() { return name; } }
然后运用TreeMap,构建目标
package TreeMap; import javax.swing.*; import javax.swing.event.TreeSelectionEvent; import javax.swing.event.TreeSelectionListener; import javax.swing.tree.DefaultMutableTreeNode; /** * Created by Mr.Yx on 2017/4/19. */ public class TreeMapDemo { public static void main(String[] args) { DefaultMutableTreeNode d1 = new DefaultMutableTreeNode("软件部"); d1.add(new DefaultMutableTreeNode(new User("小花"))); d1.add(new DefaultMutableTreeNode(new User("小虎"))); d1.add(new DefaultMutableTreeNode(new User("小龙"))); DefaultMutableTreeNode d2 = new DefaultMutableTreeNode("销售部"); d2.add(new DefaultMutableTreeNode(new User("小叶"))); d2.add(new DefaultMutableTreeNode(new User("小雯"))); d2.add(new DefaultMutableTreeNode(new User("小夏"))); DefaultMutableTreeNode top = new DefaultMutableTreeNode("职员管理"); top.add(new DefaultMutableTreeNode(new User("总经理"))); top.add(d1); top.add(d2); final JTree jTree = new JTree(top); JFrame jFrame = new JFrame("JTreeDemo"); jFrame.add(jTree); jFrame.setSize(300,400); jFrame.setVisible(true); jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); jTree.addTreeSelectionListener(new TreeSelectionListener() { @Override public void valueChanged(TreeSelectionEvent e) { DefaultMutableTreeNode defaultMutableTreeNode = (DefaultMutableTreeNode) jTree.getLastSelectedPathComponent(); if (defaultMutableTreeNode == null) return; Object object = defaultMutableTreeNode.getUserObject(); if (defaultMutableTreeNode.isLeaf()) { User user = (User) object; System.out.println("你选择了:" + user.toString()); } } }); } }