原链接见Flex Tree 实践。该文章使Tree使用ArrayCollection作数据源,结合JSON与后台j2ee交互,可以大幅减少数据长度。该文章还算不错,但代码有错误。经过改正,代码如下:
1,Node类文件
package
{
import mx.collections.ArrayCollection;
public class Node
{
public var id:String
public var name:String;
public var children:ArrayCollection;
public function Node()
{
}
}
}
2,测试代码:
<?xml version="1.0" encoding="utf-8"?>
<mx:Application creationComplete="init()" xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">
<mx:Tree x="29" y="48" width="339" height="205" id="exampleTree"></mx:Tree>
<mx:Script>
<![CDATA[
import mx.collections.ArrayCollection;
var nodes:ArrayCollection = new ArrayCollection(); //第一层树结点数据
var nodesChildren:ArrayCollection = new ArrayCollection(); //孩子结点集合
var aNode:Node = null; //树结点
function init():void{
//先准备需要的子结点数据
var aNode1:Node = new Node();
aNode1.id = "00";
aNode1.name = "孩子结点1";
aNode1.children = null; //当前结点如果没有孩子结点那么children设为null,如果有,则赋值为它的孩子集合,Flex Tree递归加载
nodesChildren.addItem(aNode1);
var aNode2:Node = new Node();
aNode2.id = "01";
aNode2.name = "孩子结点2";
aNode2.children = null;
aNode = new Node();
nodesChildren.addItem(aNode2);
//孩子结点数据准备完毕
//准备父节点数据
aNode.id = "0";
aNode.name = "父结点1";
aNode.children = nodesChildren; //在这里将父节点的孩子结点数据加进去
nodes.addItem(aNode);
aNode = new Node();
aNode.id = "1";
aNode.name = "父结点2";
aNode.children = null; //假设父节点2没有孩子结点
nodes.addItem(aNode);
//父节点数据准备完毕
//实例化一棵树
//var exampleTree:Tree = new Tree();
exampleTree.dataProvider=nodes;
exampleTree.labelField="name"; //指定显示字段
}
]]>
</mx:Script>
</mx:Application>
3,结果:
使用xml做数据源的优点是可读性好、层次清楚,但是xml的数据表示效率太低。所以我认为大量的交互还是json比较好。