日期:2014-05-20 浏览次数:20808 次
import java.awt.BorderLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JTree; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeModel; public class TestJTree extends JFrame { private JButton button ; private JTree tree ; private int treeNodeNum = 1 ; DefaultMutableTreeNode _rootNode = new DefaultMutableTreeNode("root"); DefaultTreeModel _defaultTreeModel = new DefaultTreeModel(_rootNode); public TestJTree(){ super(); this.setSize(300, 400); button = new JButton("添加树节点"); button.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent e) { DefaultMutableTreeNode _newNode = new DefaultMutableTreeNode("新添加的树节点_"+treeNodeNum); _rootNode.add(_newNode); _defaultTreeModel.reload(); treeNodeNum++; } }); tree = new JTree(); tree.setModel(_defaultTreeModel); this.getContentPane().add(tree,BorderLayout.CENTER); this.getContentPane().add(button,BorderLayout.SOUTH); } public static void main(String[] args){ TestJTree testJTree = new TestJTree(); testJTree.setVisible(true); } }