Java实现树形菜单
1.树形菜单代码思路
1.首先定义一个菜单类,定义菜单中的属性,其中属性包括ID,父ID,结点信息text信息。
2.使用一个菜单构造类来使用递归方法生成菜单。
3.输出构造完成的菜单结构。
2.实现代码
首先是菜单类的定义
public class Tree {
private String ID;//结点ID
private String ParentID;//结点父ID
private String text;//结点内容
public Tree(String ID, String ParentID, String text){
this.ID = ID;
this.ParentID = ParentID;
this.text = text;
}
public String getID(){
return this.ID;
}
public String getParentID(){
return this.ParentID;
}
public String getText(){
return this.text;
}
}
然后是菜单构造类,主要部分就是递归方法的使用。
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
public class MenuTree {
public List<Tree> menuList;//
public List<Object> treeMenus = new ArrayList<Object>();//存放树形菜单
public MenuTree(List<Tree> menu){
this.menuList = menu;
}
public List<Object> buildTree(){
for (Tree node : menuList) {
if(node.getParentID()=="0"){
Map<String,Object> treeRoot = new LinkedHashMap<String, Object>();
treeRoot.put("ID", node.getID());
treeRoot.put("text", node.getText());
treeRoot.put("parentID", node.getParentID());
treeRoot.put("childList", buildChildTree(node.getParentID()));
treeMenus.add(treeRoot);
}
}
return treeMenus;
}
public List<?> buildChildTree(String id){
List<Object> childMenus = new ArrayList<Object>();
for(Tree node:menuList){
if(node.getParentID() == id){
Map<String,Object> treeChild = new LinkedHashMap<String, Object>();
treeChild.put("ID", node.getID());
treeChild.put("text", node.getText());
treeChild.put("parentID", node.getParentID());
treeChild.put("childList", buildChildTree(node.getID()));//递归调用,获取子节点
childMenus.add(treeChild);
}
}
return childMenus;
}
}
最后是测试验证部分,输出了构造的菜单List。
import java.util.ArrayList;
import java.util.List;
/*
测试代码
*/
public class test {
public static void main(String args[]){
List<Tree> treeArray = new ArrayList<Tree>();
treeArray.add(new Tree("1","0","客户"));
treeArray.add(new Tree("2","0","管理"));
treeArray.add(new Tree("3","1","系统"));
treeArray.add(new Tree("4","3","权限"));
treeArray.add(new Tree("5","4","内容"));
MenuTree menuTree = new MenuTree(treeArray);
List<Object> treeMenu = menuTree.buildTree();
System.out.println(treeMenu);
}
}
还可以在构造菜单类方法中,将每次符合判断条件的菜单节点在menuList移除,减少递归时的循环次数。