package filechooser; import java.awt.BorderLayout; import java.awt.Color; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.Enumeration; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTree; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeCellRenderer; import javax.swing.tree.DefaultTreeModel; import javax.swing.tree.TreeNode; import javax.swing.tree.TreePath; public class FrameTreeDemo extends JPanel { private static final long serialVersionUID = 1L; DefaultMutableTreeNode root, child, chosen; JTree tree; DefaultTreeModel model; DefaultTreeCellRenderer treeRenderer = new DefaultTreeCellRenderer(); ImageIcon image1 = new ImageIcon(getClass().getResource("/image/6.gif")); ImageIcon image2 = new ImageIcon(getClass().getResource("/image/4.gif")); ImageIcon image3 = new ImageIcon(getClass().getResource("/image/5.gif")); String[][] data = { {"天峰", "山峰", "小凤", "疯疯"}, {"爱好", "劳动", "钱财", "老婆"}, {"职位", "平民", "地主", "官僚"}, {"工资", "20", "2000", "200000"}, {"职位 ", "地下", "高明", "无所不在"}, {"民用", "名义", "明信 ", "无聊"}}; static int i = 0; public FrameTreeDemo() { root = new DefaultMutableTreeNode("root"); tree = new JTree(root); treeRenderer.setClosedIcon(image1); treeRenderer.setOpenIcon(image2); treeRenderer.setLeafIcon(image3); treeRenderer.setBorder(null); treeRenderer.setToolTipText(" "); treeRenderer.setVerifyInputWhenFocusTarget(false); treeRenderer.setDisplayedMnemonic('3'); treeRenderer.setLabelFor(tree); treeRenderer.setBackgroundSelectionColor(Color.green); treeRenderer.setTextNonSelectionColor(Color.darkGray); treeRenderer.setTextSelectionColor(Color.red); tree.setCellRenderer(treeRenderer); setLayout(new BorderLayout()); add(new JScrollPane(tree)); model = (DefaultTreeModel)tree.getModel(); JButton test = new JButton("在当前节点下添加子节点 "); JPanel p = new JPanel(); p.add(test); add(p, BorderLayout.SOUTH); test.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (i < data.length) { child = new AddNode(data[i++]).node(); chosen = (DefaultMutableTreeNode)tree.getLastSelectedPathComponent(); if (chosen == null) { chosen = root; } model.insertNodeInto(child, chosen, 0); // 把child添加到chosen; } } }); expandAll(tree, true); } public void expandAll(JTree tree, boolean expand) { TreeNode root = (TreeNode)tree.getModel().getRoot(); expandAll(tree, new TreePath(root), expand); }