日期:2014-05-16 浏览次数:20439 次
来自:Extjs交流群(164648099)
?
说明:
两个文件
jackyNode.java? treeVO对象 将数据库当中的树的数据库存入此
jackytree.java? 采用递归算法 将一次性查出来的数据生成treeJSON结构
直接将两个文件复制到eclipse中? run as即可查看
?
jackyNode.java
package com.codeasy.common; public class jackyNode { private int id; private int parentId; private String text; jackyNode(){} jackyNode(int id,int parentId,String text){ this.id=id; this.parentId = parentId; this.text = text; } public int getId() { return id; } public void setId(int id) { this.id = id; } public int getParentId() { return parentId; } public void setParentId(int parentId) { this.parentId = parentId; } public String getText() { return text; } public void setText(String text) { this.text = text; } }
?
?
jackytree.java?
package com.codeasy.common; import java.util.ArrayList; import java.util.Iterator; import java.util.List; /* * 数据库中的表结构是这样的 * id parentid name * * * */ public class jackytree { List nodeList =new ArrayList(); jackytree(){//构造方法里初始化模拟List jackyNode node1 = new jackyNode(1,0,"根节点"); jackyNode node2 = new jackyNode(2,1,"一级菜单"); jackyNode node3 = new jackyNode(3,1,"一级菜单"); jackyNode node4 = new jackyNode(4,2,"二级菜单"); jackyNode node5 = new jackyNode(5,2,"二级菜单"); jackyNode node6 = new jackyNode(6,2,"二级菜单"); jackyNode node7 = new jackyNode(7,6,"三级菜单"); jackyNode node8 = new jackyNode(8,6,"三级菜单"); nodeList.add(node1); nodeList.add(node2); nodeList.add(node3); nodeList.add(node4); nodeList.add(node5); nodeList.add(node6); nodeList.add(node7); nodeList.add(node8); } StringBuffer returnStr=new StringBuffer(); public void recursionFn(List list , jackyNode node){ if(hasChild(list,node)){ returnStr.append("{id:"); returnStr.append(node.getId()); returnStr.append(",text:'"); returnStr.append(node.getText()); returnStr.append("'"); returnStr.append(",children:["); List childList = getChildList(list,node); Iterator it = childList.iterator(); while(it.hasNext()){ jackyNode n = (jackyNode)it.next(); recursionFn(list,n); } returnStr.append("]},"); }else{ returnStr.append("{id:"); returnStr.append(node.getId()); returnStr.append(",text:'"); returnStr.append(node.getText()); returnStr.append("'"); returnStr.append(",leaf:true},"); } } public boolean hasChild(List list, jackyNode node){ //判断是否有子节点 return getChildList(list,node).size()>0?true:false; } public List getChildList(List list , jackyNode node){ //得到子节点列表 List li = new ArrayList(); Iterator it = list.iterator(); while(it.hasNext()){ jackyNode n = (jackyNode)it.next(); if(n.getParentId()==node.getId()){ li.add(n); } } return li; } public String modifyStr(String returnStr){//修饰一下才能满足Extjs的Json格式 return ("["+returnStr+"]").replaceAll(",]", "]"); } public static void main(String[] args) { jackytree r = new jackytree(); r.recursionFn(r.nodeList, new jackyNode(1,0,"根节点")); System.out.println(r.modifyStr(r.returnStr.toString())); } }
?
?