上次使用的方式,思路没有问题,但是中间限制条件较多,后面再准备正式拼接机构树的时候,突然想到了递归调用,这样处理起来会方便一些。

效果图
思路: 1、传入当前节点,第一次调用传入root节点当做当前节点 2、将节点挂接在当前节点下,挂接后,判断当前节点是否有子节点,没有直接结束, 有节点,将新节点设置为当前节点 3、递归调用节点操作,传入list,当前节点 注:当前节点会有一种情况,当某分支机构树遍历结束后,当前节点会变成最后一个节点,所以机构会挂接 在最后的节点上,针对这种情况,引入了两个新的方法,节点比较,比较nowNode是否是需要挂接的节点的 父级节点,而想要通过字符串和机构树节点对比的话,只能遍历机构树,同时获得节点的UserObject属性 值(节点名称),如果是,则返回节点,不是则继续遍历直至找到父级节点,如遍历结束后仍未找到,则挂 接在root节点下
/**
* 节点操作
* @param list 数据列表
* @param rootId 上级节点ID
* @param nowNode 当前节点
*/
public static void nodeOperating(List<Map<String, Object>> list,
String rootId, DefaultMutableTreeNode nowNode) {
// 遍历机构,将机构挂接在相应机构树上
for (Map<String, Object> map : list) {
// 挂接节点
String unit_name = map.get("unit_name").toString();
System.out.println("当前机构:" + unit_name);
// 根据当前节点名称确定上级节点
nowNode = nodeEquals(nowNode,map);
System.out.println("当前节点:" + nowNode.getUserObject().toString());
DefaultMutableTreeNode newNode = new DefaultMutableTreeNode(
unit_name);
nowNode.add(newNode);
String parent_id = map.get("id").toString();
// 判断当前节点下是否有子节点
list = JDBC.query(JDBC.conn(),
SQL.selByCondition("unit", "parent_id", parent_id));
if (list.size() > 0) {
nowNode = newNode;
nodeOperating(list, parent_id, nowNode);
} else {
System.out.println("末级节点");
}
}
System.out.println("机构树挂接");
}
/**
* 节点比较
* @param nowNode 当前节点
* @param map 当前需要挂接的节点信息
* @return
*/
public static DefaultMutableTreeNode nodeEquals(DefaultMutableTreeNode nowNode,Map<String, Object> map){
DefaultMutableTreeNode node = nowNode;
// 根据当前节点名称确定上级节点,上级节点为空则挂接在根节点中
List<Map<String, Object>> list = JDBC.query(JDBC.conn(),SQL.selPraent("unit_name", map.get("parent_id").toString()));
if(list.size()>0){
String parment_name = list.get(0).get("unit_name").toString();
if (!nowNode.getUserObject().equals(parment_name)) {
System.out.println("nowNode节点与上级节点不相同");
//获取上级节点 DefaultMutableTreeNode对象
node = nodeTraversing(root, parment_name);
}
}else{
node = root;
}
return node;
}
/**
* 遍历节点
* @param root 根节点
* @param nodeName 节点名称
* @return
*/
public static DefaultMutableTreeNode nodeTraversing(DefaultMutableTreeNode root,String nodeName){
DefaultMutableTreeNode nowNode = null;
Enumeration enumeration = root.preorderEnumeration();
while(enumeration.hasMoreElements()){ //遍历枚举对象.
//先定义一个节点变量.
DefaultMutableTreeNode node;
node=(DefaultMutableTreeNode) enumeration.nextElement();//将节点名称给node.
//根据级别输出占位符.
for(int l=0;l<node.getLevel();l++){
System.out.print("---");
}
System.out.println(node.getUserObject());//输入节点标签.
if(node.getUserObject().equals(nodeName)){
nowNode = node;
return nowNode;
}
}
return root;
}





Comments | NOTHING