注释很详细,直接上代码
新增内容(一共16个常见用法,内容较多此处概述一下)
?按各类关系查询节点或节点组内容
?按各类关系查询某种关系是否成立
?按各类关系查询符合某些关系的数量
package swing41_50;
import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreeNode;
import java.util.Enumeration;
public class swing_test_41 {
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);
//设置滚动
jFrame.add(new JScrollPane(tree));
jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//关闭窗口
jFrame.pack();//自动调整窗口大小
jFrame.setVisible(true);//显示窗口
//1.获取广东的根结点:中国
System.out.println(guangdong.getRoot());;
//2.获取佛山的父结点:广东
System.out.println(foshan.getParent());
//3.获取桂林的下一个兄弟结点:南宁
System.out.println(guilin.getNextSibling());
//4.获取南宁的上一个兄弟结点:桂林
System.out.println(nanning.getPreviousSibling());
//5.获取两个结点最近的共同祖先:广西
System.out.println(guilin.getSharedAncestor(nanning));
//7.获取结点的兄弟结点数(包括自己):2
System.out.println(guilin.getSiblingCount());
//8.判断节点是否是叶子结点:ture
System.out.println(guilin.isLeaf());
//9.判断节点是否是根节点:true
System.out.println(root.isRoot());
//10.判断节点是否是指定节点的子节点:true
System.out.println(root.isNodeChild(guangdong));
//11.判断节点是否是指定节点的祖先节点:true
System.out.println(guangdong.isNodeAncestor(root));
//12.判断节点是否是指定节点的后代节点:true
System.out.println(root.isNodeDescendant(guangdong));
//13.判断节点是否是指定节点的兄弟节点:true
System.out.println(guilin.isNodeSibling(nanning));
//14.判断两个节点是否在同一棵树
System.out.println(root.isNodeRelated(nanning));
//15.按广度优先的顺序遍历以此结点为根的子树,并返回所有结点组成的枚举对象
Enumeration<TreeNode> pre = root.preorderEnumeration();
while (pre.hasMoreElements()){//遍历其中的结点
System.out.format("%s ",pre.nextElement());
}
System.out.println();
//16.按深度优先的顺序遍历以此结点为根的子树,并返回所有结点组成的枚举对象
Enumeration<TreeNode> en = root.depthFirstEnumeration();
while (en.hasMoreElements()){//遍历其中的结点
System.out.format("%s ",en.nextElement());
}
System.out.println();
//17. 返回从指定祖先结点到当前结点的所有结点组成的枚举对象,并输出
Enumeration<TreeNode> en1 = guilin.pathFromAncestorEnumeration(root);
while (en1.hasMoreElements()){//遍历其中的结点
System.out.format("%s ",en1.nextElement());
}
}
public static void main(String[] args) {
//启动程序
new swing_test_41().init();
}
}
效果演示