import javax.swing.JFrame; import javax.swing.JTree; import javax.swing.tree.DefaultMutableTreeNode; public class JTreeDemo extends JFrame{ /** * */ private static final long serialVersionUID = 1L; public JTreeDemo(){ //根节点 DefaultMutableTreeNode group =new DefaultMutableTreeNode("根节点"); //二级节点 DefaultMutableTreeNode first=new DefaultMutableTreeNode("二级节点1"); DefaultMutableTreeNode second = new DefaultMutableTreeNode("二级节点2"); DefaultMutableTreeNode thrid = new DefaultMutableTreeNode("二级节点3"); //三级节点 DefaultMutableTreeNode first1 = new DefaultMutableTreeNode("三级节点11"); DefaultMutableTreeNode first2 = new DefaultMutableTreeNode("三级节点12"); DefaultMutableTreeNode second1 = new DefaultMutableTreeNode("三级节点21"); DefaultMutableTreeNode second2 = new DefaultMutableTreeNode("三级节点22"); DefaultMutableTreeNode second3 = new DefaultMutableTreeNode("三级节点23"); DefaultMutableTreeNode thrid1 = new DefaultMutableTreeNode("三级节点31"); DefaultMutableTreeNode thrid2 = new DefaultMutableTreeNode("三级节点32"); DefaultMutableTreeNode thrid3 = new DefaultMutableTreeNode("三级节点33"); //将三级节点添加到二级节点上 first.add(first1); first.add(first2); second.add(second1); second.add(second2); second.add(second3); thrid.add(thrid1); thrid.add(thrid2); thrid.add(thrid3); //将二级节点添加到一级节点上 group.add(first); group.add(second); group.add(thrid); JTree tree = new JTree(group); //以group为参数创建根目录 tree.collapseRow(1); //总是显示根目录在前 tree.setToggleClickCount(1); //设置鼠标单击数 this.getContentPane().add(tree); setSize(300,300); setVisible(true); setTitle("树的应用"); } public static void main(String[] args) { new JTreeDemo(); } }
时间: 2024-12-23 23:08:37