import java.awt.BorderLayout; import java.awt.Color; import java.awt.Container; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTree; import javax.swing.event.CellEditorListener; import javax.swing.event.ChangeEvent; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeModel; public class Test extends JFrame{ static int i = 0; DefaultMutableTreeNode root; /* DefaultMutableTreeNode是树数据结构中的通用节点 */ DefaultMutableTreeNode child; DefaultMutableTreeNode chosen; JTree tree; DefaultTreeModel model; // 使用 TreeNodes 的简单树数据模型. String[][] data = {{"体育","足球","篮球","乒乓球"},{"娱乐","唱歌","跳舞","相声","小品"},{"电视","长虹","海尔","创维"},{"戏剧","京剧","川剧","越剧"}, {"国家","中国","越南","朝鲜","德国"},{"武器","飞机","大炮","坦克"}}; Test(){ Container contentPane = this.getContentPane(); JPanel jPanel1 = new JPanel(new BorderLayout()); root = new DefaultMutableTreeNode("根"); tree = new JTree(root); // 建立以root为根的树 jPanel1.add(new JScrollPane(tree),BorderLayout.CENTER); model = (DefaultTreeModel) tree.getModel(); for(int i = 0 ;i < data.length ; i++){ child = new Branch(data[i++]).node(); chosen = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent(); if(chosen == null){ chosen = root; } model.insertNodeInto(child,chosen,0); } JButton jButton1 = new JButton("使节点可编辑"); //使节点可编辑 jButton1.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e){ tree.setEditable(true); tree.getCellEditor().addCellEditorListener(new CellEditorAction()); tree.startEditingAtPath(tree.getSelectionPath()); } }); jButton1.setBackground(Color.blue); jButton1.setForeground(Color.white); JPanel jPanel2 = new JPanel(); jPanel2.add(jButton1); jPanel1.add(jPanel2,BorderLayout.SOUTH); contentPane.add(jPanel1); this.setTitle("JtreeDemo"); this.setSize(300,500); this.setLocation(400,400); this.setVisible(true); } class Branch{ DefaultMutableTreeNode r; public Branch(String[] data){ r = new DefaultMutableTreeNode(data[0]); for(int i = 1;i < data.length;i++){ r.add(new DefaultMutableTreeNode(data[i])); } } public DefaultMutableTreeNode node(){ return r; } } private class CellEditorAction implements CellEditorListener{ public void editingCanceled(ChangeEvent e) { System.out.println("编辑取消"); } public void editingStopped(ChangeEvent e) { System.out.println("编辑结束"); } } public static void main(String args[]){ new Test(); } }