注释很详细,直接上代码
新增内容
JTree的创建
设置节点之间的连线
设置节点之间的水平分割线
设置根节点的展开折叠图标
设置是否隐藏根节点
package swing31_40;
import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;
public class swing_test_40 {
JFrame jFrame = new JFrame("简单树");
JTree tree;
DefaultMutableTreeNode root;
DefaultMutableTreeNode guangdong;
DefaultMutableTreeNode guangxi;
DefaultMutableTreeNode foshan;
DefaultMutableTreeNode shantou;
DefaultMutableTreeNode guilin;
DefaultMutableTreeNode nanning;
public void init(){
//依次创建所有结点
root = new DefaultMutableTreeNode("中国");
guangdong = new DefaultMutableTreeNode("广东");
guangxi = new DefaultMutableTreeNode("广西");
foshan = new DefaultMutableTreeNode("佛山");
shantou = new DefaultMutableTreeNode("汕头");
guilin = new DefaultMutableTreeNode("桂林");
nanning = new DefaultMutableTreeNode("南宁");
//通过add()方法建立父子层级关系
guangdong.add(foshan);
guangdong.add(shantou);
guangxi.add(guilin);
guangxi.add(nanning);
root.add(guangdong);
root.add(guangxi);
//依据根结点,创建JTree
tree = new JTree(root);
//设置结点之间没有连接线
//tree.putClientProperty( "JTree.lineStyle", "None");
//设置结点之间有水平分割线
//tree.putClientProperty("JTree.lineStyle" , "Horizontal");
//设置根结点有"展开、折叠"图标
//tree.setShowsRootHandles(true);
//隐藏根结点
//tree.setRootVisible(false);
//设置滚动
jFrame.add(new JScrollPane(tree));
jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//关闭窗口
jFrame.pack();//自动调整窗口大小
jFrame.setVisible(true);//显示窗口
}
public static void main(String[] args) {
//启动程序
new swing_test_40().init();
}
}
演示效果:
(图片为默认的样式,其他效果已注释,需要取消注释即可)