1.首先定义根节点和叶节点
DefaultMutableTreeNode root = new DefaultMutableTreeNode("根节点");
DefaultMutableTreeNode leafNode1 = new DefaultMutableTreeNode("叶节点1");
DefaultMutableTreeNode leafNode2 = new DefaultMutableTreeNode("叶节点2");
root.add(leafNode1);
root.add(leafNode2);
2.设置树的显示风格
UIManager.getDefaults().put("Tree.lineTypeDashed", true);// 设置连接线为虚线
UIManager.getDefaults().put("Tree.lineTypeDashed",false); //设置连接线为直线
JTree tree = new JTree(root);//建树
tree.putClientProperty("JTree.lineStyle","None");//去掉连接线
tree.putClientProperty("JTree.lineStyle","Horizontal");//将树设为水平分隔风格
tree.putClientProperty("JTree.lineStyle","Angled");//默认
3.给树上节点添加图片
首先要获得树的DefaultTreeCellRenderer
DefaultTreeCellRenderer renderer = (DefaultTreeCellRenderer) tree.getCellRenderer();
Icon rootIcon = new ImageIcon("rootIcon路径");
Icon leafIcon = new ImageIcon("leafIcon路径");
添加图片
rend.setLeafIcon(leafIcon);//叶节点图片
rend.setOpenIcon(rootIcon);//树打开时显示的图片
rend.setClosedIcon(collIcon);//树关闭时显示的图片
若要隐藏根节点
tree.setRootVisible(false);
setBounds(int x, int y, int width, int height)方法的应用
很早以前就看到了这个方法,其说明:(x,y)为组件显示的坐标,(width,height)为组件的宽和高
但无论我怎么设置都没有用,知道前天看到了一个具体实例才豁然开朗,只需要加上一行代码:
this.setLayout(null);