Flex4之Tree开发

1.首先得明白一点,FLEX4的TREE接受的是XML类型的数据,所以无论以何种方式获得XML数据,TREE通过dataProvider=XMLDATA和labelField=@viewname都可以显示出来一棵树

第一种方式,读取本地或远程XML文件

XML文件的格式,大致如下

Xml代码
  1. <spanstyle="font-size: medium;"><?xmlversion="1.0"encoding="UTF-8"?> 
  2. <node  label='所有分类'> 
  3. <node  label='中国'value="http://www.baidu.com"> 
  4. <nodelabel='河南'value="http://www.youdao.com"> 
  5. <node  label='信阳'/> 
  6. <node  label='南阳'/> 
  7. </node> 
  8. <node  label='河北'> 
  9. <nodelabel='保定'/> 
  10. <node  label='衡水'/> 
  11. </node> 
  12. <nodelabel='湖南'> 
  13. <nodelabel='长沙'/> 
  14. <node  label='湘潭'/> 
  15. </node> 
  16. <nodelabel='湖北'> 
  17. <nodelabel='武汉'/> 
  18. <nodelabel='仙桃'/> 
  19. </node> 
  20. </node> 
  21. </node></span> 
<?xml version="1.0" encoding="UTF-8"?>
<node  label='所有分类'>
<node  label='中国' value="http://www.baidu.com">
<node label='河南' value="http://www.youdao.com" >
<node  label='信阳' />
<node  label='南阳'/>
</node>
<node  label='河北'>
<node label='保定'/>
<node  label='衡水'/>
</node>
<node label='湖南' >
<node label='长沙'/>
<node  label='湘潭'/>
</node>
<node label='湖北'>
<node label='武汉'/>
<node label='仙桃'/>
</node>
</node>
</node>

针对上面这个XML格式的文件,Flex4的TREE解析后显示的话会从第二个节点开始解析也即中国那个节点 这种方式的代码我贴出来,大家看下

Xml代码
  1. <spanstyle="font-size: medium;"><?xmlversion="1.0"encoding="utf-8"?> 
  2. <s:Applicationxmlns:fx="http://ns.adobe.com/mxml/2009"  
  3.                xmlns:s="library://ns.adobe.com/flex/spark"  
  4.                xmlns:mx="library://ns.adobe.com/flex/mx"minWidth="955"minHeight="600" 
  5.                creationComplete="SrvTreeList.send();init()"> 
  6.     <fx:Style> 
  7.         Tree { 
  8.         folderClosedIcon: ClassReference(null); 
  9.         folderOpenIcon: ClassReference(null); 
  10.         } 
  11.     </fx:Style> 
  12.  
  13.     <fx:Script> 
  14.         <![CDATA[
  15.             import mx.collections.ArrayCollection;
  16.             import mx.rpc.events.ResultEvent;
  17.             var XMLTreeList:XML;
  18.             protected function treeService_resultHandler(event:ResultEvent):void
  19.             {  
  20.                 //先把数据取出来交给XML,再交给dataProvider,因为dataProvider不能直接解析String为XML
  21.                 XMLTreeList=XML(SrvTreeList.lastResult.toString());
  22.                 MusicTypeTree.dataProvider=XMLTreeList;
  23.             }
  24.                         //这里我写了一个右键菜单      
  25.                        public function init():void{
  26.            
  27.              var item: ContextMenuItem=new ContextMenuItem("添加");
  28.              var menu:ContextMenu=new ContextMenu();
  29.              menu.customItems.push(item);
  30.              MusicTypeTree.contextMenu=menu;
  31.             }
  32.             protected function tree1_clickHandler(event:MouseEvent):void
  33.             {
  34.                 if(MusicTypeTree.selectedItem.hasOwnProperty("@value" ))
  35.                    
  36.                 {       //如果某节点中含有VALUE属性,那么就是先跳转页面
  37.                     navigateToURL(new URLRequest(MusicTypeTree.selectedItem.@value));
  38.                 } else
  39.                 {
  40.                     //没有那就展开,如果展开了就收缩
  41.                     MusicTypeTree.expandItem(MusicTypeTree.selectedItem,!MusicTypeTree.isItemOpen(MusicTypeTree.selectedItem),true);
  42.                 }
  43.             }
  44.         ]]> 
  45.     </fx:Script> 
  46.     <fx:Declarations> 
  47.         <!-- 将非可视元素(例如服务、值对象)放在此处 --> 
  48.         <s:HTTPService  id="SrvTreeList"url="data/tree.xml"result="treeService_resultHandler(event)"useProxy="false"  resultFormat="xml"/> 
  49.     </fx:Declarations> 
  50.     <!--@label这个非常重要,指定要显示的标题为XML重的label属性值。记住要显示树,httpService的send方法要在组件创建完成后被调用--> 
  51.     <mx:Treex="20"y="10"click="tree1_clickHandler(event)"id="MusicTypeTree" 
  52.              left="5"right="5"  
  53.              showRoot="false"  
  54.              labelField="@label"          
  55.              bottom="5"top="40" 
  56.               
  57.              ></mx:Tree> 
  58.      
  59. </s:Application> 
  60. </span> 
<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" 
			   xmlns:s="library://ns.adobe.com/flex/spark" 
			   xmlns:mx="library://ns.adobe.com/flex/mx" minWidth="955" minHeight="600"
			   creationComplete="SrvTreeList.send();init()">
	<fx:Style>
		Tree {
		folderClosedIcon: ClassReference(null);
		folderOpenIcon: ClassReference(null);
		}
	</fx:Style>

	<fx:Script>
		<![CDATA[
			import mx.collections.ArrayCollection;
			import mx.rpc.events.ResultEvent;

			var XMLTreeList:XML;
			protected function treeService_resultHandler(event:ResultEvent):void
			{   
				//先把数据取出来交给XML,再交给dataProvider,因为dataProvider不能直接解析String为XML
				XMLTreeList=XML(SrvTreeList.lastResult.toString()); 
				MusicTypeTree.dataProvider=XMLTreeList; 

			}
                        //这里我写了一个右键菜单		
                       public function init():void{
			
			 var item: ContextMenuItem=new ContextMenuItem("添加");
			 var menu:ContextMenu=new ContextMenu();
			 menu.customItems.push(item);
			 MusicTypeTree.contextMenu=menu;
			}



			protected function tree1_clickHandler(event:MouseEvent):void
			{
				if(MusicTypeTree.selectedItem.hasOwnProperty("@value" ))
					
				{       //如果某节点中含有VALUE属性,那么就是先跳转页面
					navigateToURL(new URLRequest(MusicTypeTree.selectedItem.@value)); 
				} else
				{ 
					//没有那就展开,如果展开了就收缩
					MusicTypeTree.expandItem(MusicTypeTree.selectedItem,!MusicTypeTree.isItemOpen(MusicTypeTree.selectedItem),true);
				} 
			}

		]]>
	</fx:Script>
	<fx:Declarations>
		<!-- 将非可视元素(例如服务、值对象)放在此处 -->
		<s:HTTPService  id="SrvTreeList" url="data/tree.xml" result="treeService_resultHandler(event)" useProxy="false"  resultFormat="xml" />
	</fx:Declarations>
	<!--@label这个非常重要,指定要显示的标题为XML重的label属性值。记住要显示树,httpService的send方法要在组件创建完成后被调用-->
	<mx:Tree x="20" y="10" click="tree1_clickHandler(event)" id="MusicTypeTree"
			 left="5" right="5" 
			 showRoot="false" 
			 labelField="@label"         
			 bottom="5" top="40"
			 
			 ></mx:Tree>
	
</s:Application>

 

 

第二种方式:将XML内容写到<fx:mxl>标签里面 这种方式我们来看看

Xml代码
  1. <spanstyle="font-size: medium;"><?xmlversion="1.0"encoding="utf-8"?> 
  2. <s:Applicationxmlns:fx="http://ns.adobe.com/mxml/2009"  
  3.                xmlns:s="library://ns.adobe.com/flex/spark"  
  4.                xmlns:mx="library://ns.adobe.com/flex/mx"minWidth="955"minHeight="600" 
  5.                creationComplete="init()"> 
  6.     <fx:Declarations> 
  7.         <!-- 将非可视元素(例如服务、值对象)放在此处 --> 
  8.     </fx:Declarations> 
  9. <fx:Script> 
  10.     <![CDATA[
  11.         import mx.collections.ICollectionView;
  12.         import mx.events.ListEvent;
  13.         private function tree_itemClick(evt:ListEvent):void {
  14.             var item:Object = Tree(evt.currentTarget).selectedItem;
  15.             if (tree.dataDescriptor.isBranch(item)) {
  16.                 tree.expandItem(item, !tree.isItemOpen(item), true);
  17.             }
  18.         }
  19.         private function tree_labelFunc(item:XML):String {
  20.             var children:ICollectionView;
  21.             var suffix:String = "";
  22.             if (tree.dataDescriptor.isBranch(item)) {
  23.                 children = tree.dataDescriptor.getChildren(item);
  24.                 suffix = " (" + children.length + ")";
  25.             }
  26.             return item[tree.labelField] + suffix;
  27.         }
  28.        
  29.        
  30.     ]]> 
  31. </fx:Script> 
  32.     <fx:Declarations> 
  33.          
  34.  
  35.     <fx:XMLid="dp"> 
  36.         <root> 
  37.             <folderlabel="One"> 
  38.                 <folderlabel="One.A"> 
  39.                     <itemlabel="One.A.1"/> 
  40.                     <itemlabel="One.A.2"/> 
  41.                     <itemlabel="One.A.3"/> 
  42.                     <itemlabel="One.A.4"/> 
  43.                     <itemlabel="One.A.5"/> 
  44.                 </folder> 
  45.                 <itemlabel="One.1"/> 
  46.                 <itemlabel="One.2"/> 
  47.             </folder> 
  48.             <folderlabel="Two"> 
  49.                 <itemlabel="Two.1"/> 
  50.                 <folderlabel="Two.A"> 
  51.                     <itemlabel="Two.A.1"/> 
  52.                     <itemlabel="Two.A.2"/> 
  53.                 </folder> 
  54.             </folder> 
  55.         </root> 
  56.     </fx:XML> 
  57.     </fx:Declarations> 
  58.     <mx:Treeid="tree" 
  59.              dataProvider="{dp}" 
  60.              showRoot="false" 
  61.              labelField="@label" 
  62.              labelFunction="tree_labelFunc" 
  63.              width="742" 
  64.              rowCount="6" 
  65.              itemClick="tree_itemClick(event);"  x="14"y="12"height="359"/> 
  66.      
  67. </s:Application> 
  68.  
  69. </span> 
<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" 
			   xmlns:s="library://ns.adobe.com/flex/spark" 
			   xmlns:mx="library://ns.adobe.com/flex/mx" minWidth="955" minHeight="600"
			   creationComplete="init()">
	<fx:Declarations>
		<!-- 将非可视元素(例如服务、值对象)放在此处 -->
	</fx:Declarations>
<fx:Script>
	<![CDATA[
		import mx.collections.ICollectionView;
		import mx.events.ListEvent;
		private function tree_itemClick(evt:ListEvent):void {
			var item:Object = Tree(evt.currentTarget).selectedItem;
			if (tree.dataDescriptor.isBranch(item)) {
				tree.expandItem(item, !tree.isItemOpen(item), true);
			}
		}
		private function tree_labelFunc(item:XML):String {
			var children:ICollectionView;
			var suffix:String = "";
			if (tree.dataDescriptor.isBranch(item)) {
				children = tree.dataDescriptor.getChildren(item);
				suffix = " (" + children.length + ")";
			}
			return item[tree.labelField] + suffix;
		}
		
		
	]]>
</fx:Script>
	<fx:Declarations>
		

	<fx:XML id="dp">
		<root>
			<folder label="One">
				<folder label="One.A">
					<item label="One.A.1" />
					<item label="One.A.2" />
					<item label="One.A.3" />
					<item label="One.A.4" />
					<item label="One.A.5" />
				</folder>
				<item label="One.1" />
				<item label="One.2" />
			</folder>
			<folder label="Two">
				<item label="Two.1" />
				<folder label="Two.A">
					<item label="Two.A.1" />
					<item label="Two.A.2" />
				</folder>
			</folder>
		</root>
	</fx:XML>
	</fx:Declarations>
	<mx:Tree id="tree"
			 dataProvider="{dp}"
			 showRoot="false"
			 labelField="@label"
			 labelFunction="tree_labelFunc"
			 width="742"
			 rowCount="6"
			 itemClick="tree_itemClick(event);"  x="14" y="12" height="359"/>
	
</s:Application>

 

Flex4之Tree开发_第1张图片

itemClick方法可以和labelFuntion可以不写,正常的话不写方法就能显示TREE的树形结构了

第三:再看一个例子

Xml代码
  1. <spanstyle="font-size: medium;"><?xmlversion="1.0"encoding="utf-8"?> 
  2. <s:Applicationxmlns:fx="http://ns.adobe.com/mxml/2009"  
  3.                xmlns:s="library://ns.adobe.com/flex/spark"  
  4.                xmlns:mx="library://ns.adobe.com/flex/mx"minWidth="955"minHeight="600"> 
  5.     <fx:Declarations> 
  6.         <!-- 将非可视元素(例如服务、值对象)放在此处 --> 
  7.         <fx:XMLListid="treeData">   
  8.             <nodelabel="Mail Box">   
  9.                 <nodelabel="Inbox">   
  10.                     <nodelabel="Marketing"/>   
  11.                     <nodelabel="Product Management"/>   
  12.                     <nodelabel="Personal"/>   
  13.                 </node>   
  14.                 <nodelabel="Outbox">   
  15.                     <nodelabel="Professional"/>   
  16.                     <nodelabel="Personal"/>   
  17.                 </node>   
  18.                 <nodelabel="Spam"/>   
  19.                 <nodelabel="Sent"/>   
  20.             </node>      
  21.         </fx:XMLList>   
  22.     </fx:Declarations> 
  23.     <fx:Script> 
  24.         <![CDATA[
  25.             [Bindable]
  26.             public var selectedNode:XML;
  27.            
  28.             // Event handler for the Tree control change event.
  29.             public function treeChanged(event:Event):void {
  30.                 selectedNode=Tree(event.target).selectedItem as XML;
  31.             }
  32.         ]]> 
  33.     </fx:Script> 
  34.     <mx:Paneltitle="Tree Control Example"height="75%"width="75%"    
  35.               paddingTop="10"paddingLeft="10"paddingRight="10"paddingBottom="10">   
  36.          
  37.         <mx:Labelwidth="100%"color="blue"    
  38.                   text="Select a node in the Tree control."/>   
  39.          
  40.         <mx:HDividedBoxwidth="100%"height="100%">   
  41.             <mx:Treeid="myTree"width="50%"height="100%"labelField="@label"   
  42.                      showRoot="false"dataProvider="{treeData}"change="treeChanged(event)"/>   
  43.             <mx:TextAreaheight="100%"width="50%"   
  44.                          text="Selected Item: {selectedNode.@label}"/>   
  45.         </mx:HDividedBox>   
  46.          
  47.     </mx:Panel>   
  48. </s:Application></span> 
<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" 
			   xmlns:s="library://ns.adobe.com/flex/spark" 
			   xmlns:mx="library://ns.adobe.com/flex/mx" minWidth="955" minHeight="600">
	<fx:Declarations>
		<!-- 将非可视元素(例如服务、值对象)放在此处 -->
		<fx:XMLList id="treeData">  
			<node label="Mail Box">  
				<node label="Inbox">  
					<node label="Marketing"/>  
					<node label="Product Management"/>  
					<node label="Personal"/>  
				</node>  
				<node label="Outbox">  
					<node label="Professional"/>  
					<node label="Personal"/>  
				</node>  
				<node label="Spam"/>  
				<node label="Sent"/>  
			</node>     
		</fx:XMLList>  
	</fx:Declarations>
	<fx:Script>
		<![CDATA[
			[Bindable] 
			public var selectedNode:XML; 
			
			// Event handler for the Tree control change event. 
			public function treeChanged(event:Event):void { 
				selectedNode=Tree(event.target).selectedItem as XML; 
			} 
		]]>
	</fx:Script>
	<mx:Panel title="Tree Control Example" height="75%" width="75%"   
			  paddingTop="10" paddingLeft="10" paddingRight="10" paddingBottom="10">  
		
		<mx:Label width="100%" color="blue"   
				  text="Select a node in the Tree control."/>  
		
		<mx:HDividedBox width="100%" height="100%">  
			<mx:Tree id="myTree" width="50%" height="100%" labelField="@label"  
					 showRoot="false" dataProvider="{treeData}" change="treeChanged(event)"/>  
			<mx:TextArea height="100%" width="50%"  
						 text="Selected Item: {selectedNode.@label}"/>  
		</mx:HDividedBox>  
		
	</mx:Panel>  
</s:Application>

Flex4之Tree开发_第2张图片

第四,到目前为止,应该可以看出来了XML的显示格式了,如果获取XML文件那么结果要转换成为 var xmlList:XML=XML(event.result.toString()); mytree.dataProvider=xmlList; 要么就是<mx:Tree dataProvider="{xmlList}" > 那么就是 <fx:xml id="xmlid"></fx:xml> <mx:Tree dataProvider="{xmlid}">

这么多的方式都可以把数据填充到TREE中去

第五:来一个增删拖拽展开,收缩的示例,这里先不涉及到后台,下一篇文章会讲到TREE与JAVA后台数据库的交互操作

Xml代码
  1. <spanstyle="font-size: medium;"><?xmlversion="1.0"encoding="utf-8"?> 
  2. <s:Applicationxmlns:fx="http://ns.adobe.com/mxml/2009"  
  3.                xmlns:s="library://ns.adobe.com/flex/spark"  
  4.                xmlns:mx="library://ns.adobe.com/flex/mx"minWidth="955"minHeight="600" 
  5.                creationComplete="SrvTreeList.send();init()"> 
  6.     <fx:Style> 
  7.         Tree { 
  8.         folderClosedIcon: ClassReference(null); 
  9.         folderOpenIcon: ClassReference(null); 
  10.         } 
  11.     </fx:Style> 
  12.  
  13.     <fx:Script> 
  14.         <![CDATA[
  15.             import mx.collections.ArrayCollection;
  16.             import mx.controls.Alert;
  17.             import mx.core.DragSource;
  18.             import mx.core.UIComponent;
  19.             import mx.events.DragEvent;
  20.             import mx.managers.DragManager;
  21.             import mx.rpc.events.ResultEvent;
  22.             var XMLTreeList:XML;
  23.             protected function treeService_resultHandler(event:ResultEvent):void
  24.             {  
  25.                 //先把数据取出来交给XML,再交给dataProvider,因为dataProvider不能直接解析String为XML
  26.                 XMLTreeList=XML(SrvTreeList.lastResult.toString());
  27.                 MusicTypeTree.dataProvider=XMLTreeList;
  28.             }
  29.             public function init():void{
  30.            
  31.              var item: ContextMenuItem=new ContextMenuItem("添加");
  32.              var menu:ContextMenu=new ContextMenu();
  33.              menu.customItems.push(item);
  34.              MusicTypeTree.contextMenu=menu;
  35.             }
  36.             protected function tree1_clickHandler(event:MouseEvent):void
  37.             {
  38.                 if(MusicTypeTree.selectedItem.hasOwnProperty("@value" ))
  39.                 {
  40.                    
  41.                     var u:URLRequest=new URLRequest(MusicTypeTree.selectedItem.@value);
  42.                     //navigateToURL(new URLRequest(MusicTypeTree.selectedItem.@value));
  43.                     navigateToURL(u);
  44.                 } else
  45.                 {
  46.                     //没有那就展开,如果展开了就收缩
  47.                     MusicTypeTree.expandItem(MusicTypeTree.selectedItem,!MusicTypeTree.isItemOpen(MusicTypeTree.selectedItem),true);
  48.                 }
  49.             }
  50.             //添加兄弟节点
  51.             protected function addBefore():void
  52.             {
  53.                 var xml:XML=MusicTypeTree.selectedItem as XML;
  54.                 var text:String=nextName.text;
  55.                 if(xml!=null && text.length>0) {
  56.                     var parent:XML=xml.parent();
  57.                     if(parent!=null) {
  58.                         var child:XML=new XML("<node foddersortName=\"\" foddersortId=\"\"  parentid=\"\" />");
  59.                         child.@foddersortName=text;
  60.                         parent.insertChildBefore(xml,child);
  61.                     } else {
  62.                         Alert.show("不能选中根节点");
  63.                     }
  64.                 } else {
  65.                     Alert.show("需要先选中节点和填入文字");
  66.                 }
  67.             }
  68.            
  69.             protected function addAfter():void
  70.             {
  71.                 var xml:XML=MusicTypeTree.selectedItem as XML;
  72.                 var text:String=nextName.text;
  73.                 if(xml!=null && text.length>0) {
  74.                     var parent:XML=xml.parent();
  75.                     if(parent!=null) {
  76.                         var child:XML=new XML("<node foddersortName=\"\" foddersortId=\"\"  parentid=\"\" />");
  77.                         child.@foddersortName=text;
  78.                         parent.insertChildAfter(xml,child);
  79.                     } else {
  80.                         Alert.show("不能选中根节点");
  81.                     }
  82.                 } else {
  83.                     Alert.show("需要先选中节点和填入文字");
  84.                 }
  85.             }
  86.            
  87.             protected function addSon():void
  88.             {
  89.                 var xml:XML=MusicTypeTree.selectedItem as XML;
  90.                 var text:String=nextName.text;
  91.                 if(xml!=null && text.length>0) {
  92.                     var parent:XML=xml.parent();
  93.                     var child:XML=new XML("<node foddersortName=\"\" foddersortId=\"\"  parentid=\"\" />");
  94.                     child.@foddersortName=text;
  95.                     xml.appendChild(child);
  96.                     MusicTypeTree.expandChildrenOf(xml,true);
  97.                 } else {
  98.                     Alert.show("需要先选中节点和填入文字");
  99.                 }          
  100.             }
  101.             protected function editNode():void
  102.             {
  103.                 var xml:XML=MusicTypeTree.selectedItem as XML;
  104.                 var text:String=nextName.text;
  105.                 if(xml!=null && text.length>0) {
  106.                     xml.@foddersortName=text;
  107.                 } else {
  108.                     Alert.show("需要先选中节点和填入文字");
  109.                 }          
  110.             }
  111.             protected function deleteNode():void
  112.             {
  113.                 var xml:XML=MusicTypeTree.selectedItem as XML;
  114.                 if(xml!=null) {
  115.                     var list:Array=MusicTypeTree.selectedItems as Array;
  116.                     for(var k:int=0;k<list.length;k++) {
  117.                         xml=list[k] as XML;
  118.                         var parent:XML=xml.parent();
  119.                         if(parent!=null) {
  120.                             var children:XMLList=parent.children();
  121.                             for(var i:int=0;i<children.length();i++) {
  122.                                 if(children[i]==xml) {
  123.                                     delete children[i];
  124.                                     break;
  125.                                 }
  126.                             }
  127.                         } else {
  128.                             Alert.show("不能选中根节点");
  129.                         }
  130.                     }
  131.                 } else {
  132.                     Alert.show("需要先选中节点");
  133.                 }          
  134.             }
  135.             protected function selectNode():void
  136.             {
  137.                 var text:String=nextName.text;
  138.                 if(text.length>0) {
  139.                     var items:Array=[];
  140.                     var list:XMLList=new XMLList();
  141.                     list[0]=MusicTypeTree.dataProvider[0];             
  142.                     searchItems(list,text,items);
  143.                     MusicTypeTree.selectedItems=items;
  144.                 } else {
  145.                     Alert.show("输入查找的文字");
  146.                 }
  147.             }
  148.             private function searchItems(list:XMLList,find:String,items:Array):void {
  149.                 for(var i:int=0;i<list.length();i++) {
  150.                     var one:XML=list[i];
  151.                     var label:String=one.@foddersortName;
  152.                     if(label!=null && label.indexOf(find)>=0) {
  153.                         items.push(one);
  154.                     }
  155.                     searchItems(one.children(),find,items);
  156.                 }
  157.             }
  158.            
  159.            
  160.            
  161.             protected function closeAll():void{
  162.                 MusicTypeTree.openItems=[];
  163.            
  164.             }
  165.            
  166.             protected function openAll():void{
  167.            
  168.                
  169.                 MusicTypeTree.expandChildrenOf(MusicTypeTree.selectedItem,true);
  170.             }
  171.             protected function MusicTypeTree_dragEnterHandler(event:DragEvent):void
  172.             {
  173.                 Alert.show(event.target.@foddersortName);
  174.                 DragManager.acceptDragDrop(UIComponent(event.currentTarget));
  175.             }
  176.             protected function MusicTypeTree_dragOverHandler(event:DragEvent):void
  177.             {
  178.                
  179.                 // r is the visible index in the tree
  180.                 var dropTarget:Tree = Tree(event.currentTarget);
  181.            
  182.                 var r:int = dropTarget.calculateDropIndex(event);
  183.                 MusicTypeTree.selectedIndex = r;
  184.            
  185.                 // retrieving the newly selected node, you can examine it and decide to tell
  186.                 // the user the drop is invalid by changing the feedback.
  187.                 var node:XML = MusicTypeTree.selectedItem as XML;
  188.                 if( node.@foddersortName == "中国" ) {
  189.                     DragManager.showFeedback(DragManager.NONE);
  190.                     return;
  191.                 }
  192.                 // the type of drop - copy, link, or move can be reflected in the feedback as well.
  193.                 // Here the control and shift keys determine that action.
  194.                 if (event.ctrlKey)
  195.                     DragManager.showFeedback(DragManager.COPY);
  196.                 else if (event.shiftKey)
  197.                     DragManager.showFeedback(DragManager.LINK);
  198.                 else {
  199.                     DragManager.showFeedback(DragManager.MOVE);
  200.                 }
  201.             }
  202.             protected function MusicTypeTree_dragDropHandler(event:DragEvent):void
  203.             {
  204.                 var xml:XML=MusicTypeTree.selectedItem as XML;
  205.                 Alert.show(xml.@foddersortName);
  206. //              var ds:DragSource = event.dragSource;
  207. //              var dropTarget:Tree = Tree(event.currentTarget);
  208. //              // retrieve the data associated with the "items" format. This will be the data that
  209. //              // the dragInitiator has copied into the DragSource.
  210. //              var items:Array = ds.dataForFormat("items") as Array;
  211. //              // determine where in the tree the drop occurs and select that node by the index; followed by
  212. //              // retrieving the node itself.
  213. //              var r:int = MusicTypeTree.calculateDropIndex(event);
  214. //              MusicTypeTree.selectedIndex = r;
  215. //              var node:XML = MusicTypeTree.selectedItem as XML;
  216. //              var p:*;
  217. //              // if the selected node has children (it is type==city),
  218. //              // then add the items at the beginning
  219. //              if( MusicTypeTree.dataDescriptor.hasChildren(node) ) {
  220. //                  p = node;
  221. //                  r = 0;
  222. //              } else {
  223. //                  p = node.parent();
  224. //              }
  225. //              // taking all of the items in the DragSouce, insert them into the
  226. //              // tree using parent p.
  227. //              for(var i:Number=0; i < items.length; i++) {
  228. //                  var insert:XML = <node />;
  229. //                  insert.@foddersortName= items[i];
  230. //                  //insert.@type = "restaurant";
  231. //                  MusicTypeTree.dataDescriptor.addChildAt(p, insert, r+i);
  232. //              }
  233.             }
  234.             protected function MusicTypeTree_dragCompleteHandler(event:DragEvent):void
  235.             {
  236.                 MusicTypeTree.selectedIndex = -1;
  237.             }
  238.         ]]> 
  239.     </fx:Script> 
  240.     <fx:Declarations> 
  241.         <!-- 将非可视元素(例如服务、值对象)放在此处 --> 
  242.         <s:HTTPService  id="SrvTreeList"url="data/tree.xml"result="treeService_resultHandler(event)"useProxy="false"  resultFormat="xml"/> 
  243.     </fx:Declarations> 
  244.     <!--@label这个非常重要,指定要显示的标题为XML重的label属性值。记住要显示树,httpService的send方法要在组件创建完成后被调用--> 
  245.     <mx:Treeclick="tree1_clickHandler(event)"id="MusicTypeTree" 
  246.              left="5"right="845"  
  247.              showRoot="false"  
  248.              labelField="@foddersortName"          
  249.              bottom="243"top="40" 
  250.              dragEnabled="true" 
  251.              dropEnabled="true" 
  252.              allowMultipleSelection="true" 
  253.              allowDragSelection="true" 
  254.              dragDrop="MusicTypeTree_dragDropHandler(event)" 
  255.              dragEnter="MusicTypeTree_dragEnterHandler(event)" 
  256.              ></mx:Tree> 
  257.     <s:TextInputid="nextName"x="432"y="40"/> 
  258.     <s:Buttonx="443"y="82"label="增加为哥"click="addBefore()"/> 
  259.     <s:Buttonx="443"y="111"label="增加为弟"click="addAfter()"/> 
  260.     <s:Buttonx="444"y="144"click="addSon()"label="增加为孩子"/> 
  261.     <s:Buttonx="444"y="178"click="editNode()"label="修改节点"/> 
  262.     <s:Buttonx="444"y="211"click="deleteNode()"label="删除节点"/> 
  263.     <s:Buttonx="443"y="244"click="selectNode()"label="选择节点"/> 
  264.     <s:Buttonx="443"y="277"click="closeAll()"label="全部收缩"/> 
  265.     <s:Buttonx="443"y="306"click="openAll()"label="全部展开"/> 
  266.      
  267. </s:Application> 
  268. </span> 
<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" 
			   xmlns:s="library://ns.adobe.com/flex/spark" 
			   xmlns:mx="library://ns.adobe.com/flex/mx" minWidth="955" minHeight="600"
			   creationComplete="SrvTreeList.send();init()">
	<fx:Style>
		Tree {
		folderClosedIcon: ClassReference(null);
		folderOpenIcon: ClassReference(null);
		}
	</fx:Style>

	<fx:Script>
		<![CDATA[
			import mx.collections.ArrayCollection;
			import mx.controls.Alert;
			import mx.core.DragSource;
			import mx.core.UIComponent;
			import mx.events.DragEvent;
			import mx.managers.DragManager;
			import mx.rpc.events.ResultEvent;

			var XMLTreeList:XML;
			protected function treeService_resultHandler(event:ResultEvent):void
			{   
				//先把数据取出来交给XML,再交给dataProvider,因为dataProvider不能直接解析String为XML
				XMLTreeList=XML(SrvTreeList.lastResult.toString()); 
				MusicTypeTree.dataProvider=XMLTreeList; 

			}

			public function init():void{
			
			 var item: ContextMenuItem=new ContextMenuItem("添加");
			 var menu:ContextMenu=new ContextMenu();
			 menu.customItems.push(item);
			 MusicTypeTree.contextMenu=menu;
			}



			protected function tree1_clickHandler(event:MouseEvent):void
			{
				if(MusicTypeTree.selectedItem.hasOwnProperty("@value" ))
				{ 
					
					var u:URLRequest=new URLRequest(MusicTypeTree.selectedItem.@value);
					//navigateToURL(new URLRequest(MusicTypeTree.selectedItem.@value)); 
					navigateToURL(u);
				} else
				{ 
					//没有那就展开,如果展开了就收缩
					MusicTypeTree.expandItem(MusicTypeTree.selectedItem,!MusicTypeTree.isItemOpen(MusicTypeTree.selectedItem),true);
				} 
			}

            //添加兄弟节点
			protected function addBefore():void
			{
				var xml:XML=MusicTypeTree.selectedItem as XML;
				var text:String=nextName.text;
				if(xml!=null && text.length>0) {
					var parent:XML=xml.parent();
					if(parent!=null) {
						var child:XML=new XML("<node foddersortName=\"\" foddersortId=\"\"  parentid=\"\" />");
						child.@foddersortName=text;
						parent.insertChildBefore(xml,child);
					} else {
						Alert.show("不能选中根节点");
					}
				} else {
					Alert.show("需要先选中节点和填入文字");
				}
			}
			
			protected function addAfter():void
			{
				var xml:XML=MusicTypeTree.selectedItem as XML;
				var text:String=nextName.text;
				if(xml!=null && text.length>0) {
					var parent:XML=xml.parent();
					if(parent!=null) {
						var child:XML=new XML("<node foddersortName=\"\" foddersortId=\"\"  parentid=\"\" />");
						child.@foddersortName=text;
						parent.insertChildAfter(xml,child);
					} else {
						Alert.show("不能选中根节点");
					}
				} else {
					Alert.show("需要先选中节点和填入文字");
				}
			}
			
			protected function addSon():void
			{
				var xml:XML=MusicTypeTree.selectedItem as XML;
				var text:String=nextName.text;
				if(xml!=null && text.length>0) {
					var parent:XML=xml.parent();
					var child:XML=new XML("<node foddersortName=\"\" foddersortId=\"\"  parentid=\"\" />");
					child.@foddersortName=text;
					xml.appendChild(child);
					MusicTypeTree.expandChildrenOf(xml,true);
				} else {
					Alert.show("需要先选中节点和填入文字");
				}			
			}
			protected function editNode():void
			{
				var xml:XML=MusicTypeTree.selectedItem as XML;
				var text:String=nextName.text;
				if(xml!=null && text.length>0) {
					xml.@foddersortName=text;
				} else {
					Alert.show("需要先选中节点和填入文字");
				}			
			}
			protected function deleteNode():void
			{
				var xml:XML=MusicTypeTree.selectedItem as XML;
				if(xml!=null) {
					var list:Array=MusicTypeTree.selectedItems as Array;
					for(var k:int=0;k<list.length;k++) {
						xml=list[k] as XML;
						var parent:XML=xml.parent();
						if(parent!=null) {
							var children:XMLList=parent.children();
							for(var i:int=0;i<children.length();i++) {
								if(children[i]==xml) {
									delete children[i];
									break;
								}
							}
						} else {
							Alert.show("不能选中根节点");
						}
					}
				} else {
					Alert.show("需要先选中节点");
				}			
			}
			protected function selectNode():void
			{
				var text:String=nextName.text;
				if(text.length>0) {
					var items:Array=[];
					var list:XMLList=new XMLList();
					list[0]=MusicTypeTree.dataProvider[0];				
					searchItems(list,text,items);
					MusicTypeTree.selectedItems=items;
				} else {
					Alert.show("输入查找的文字");
				}
			}
			private function searchItems(list:XMLList,find:String,items:Array):void {
				for(var i:int=0;i<list.length();i++) {
					var one:XML=list[i];
					var label:String=one.@foddersortName;
					if(label!=null && label.indexOf(find)>=0) {
						items.push(one);
					}
					searchItems(one.children(),find,items);
				}
			}
			
			
			
			protected function closeAll():void{
				MusicTypeTree.openItems=[];
			
			}
			
			protected function openAll():void{
			
				
				MusicTypeTree.expandChildrenOf(MusicTypeTree.selectedItem,true);
			}


			protected function MusicTypeTree_dragEnterHandler(event:DragEvent):void
			{
				Alert.show(event.target.@foddersortName);
				DragManager.acceptDragDrop(UIComponent(event.currentTarget));
			}


			protected function MusicTypeTree_dragOverHandler(event:DragEvent):void
			{
				
				// r is the visible index in the tree 
				var dropTarget:Tree = Tree(event.currentTarget);
			
				var r:int = dropTarget.calculateDropIndex(event);
				MusicTypeTree.selectedIndex = r;
			
				// retrieving the newly selected node, you can examine it and decide to tell 
				// the user the drop is invalid by changing the feedback.
				var node:XML = MusicTypeTree.selectedItem as XML;
				if( node.@foddersortName == "中国" ) {
					DragManager.showFeedback(DragManager.NONE);
					return;
				}
				// the type of drop - copy, link, or move can be reflected in the feedback as well. 
				// Here the control and shift keys determine that action. 
				if (event.ctrlKey)
					DragManager.showFeedback(DragManager.COPY);
				else if (event.shiftKey)
					DragManager.showFeedback(DragManager.LINK);
				else {
					DragManager.showFeedback(DragManager.MOVE);
				}

			}


			protected function MusicTypeTree_dragDropHandler(event:DragEvent):void
			{
				var xml:XML=MusicTypeTree.selectedItem as XML;
				Alert.show(xml.@foddersortName);
//				var ds:DragSource = event.dragSource;
//				var dropTarget:Tree = Tree(event.currentTarget);
//				// retrieve the data associated with the "items" format. This will be the data that
//				// the dragInitiator has copied into the DragSource.
//				var items:Array = ds.dataForFormat("items") as Array;
//				// determine where in the tree the drop occurs and select that node by the index; followed by 
//				// retrieving the node itself. 
//				var r:int = MusicTypeTree.calculateDropIndex(event);
//				MusicTypeTree.selectedIndex = r;
//				var node:XML = MusicTypeTree.selectedItem as XML;
//				var p:*;
//				// if the selected node has children (it is type==city),
//				// then add the items at the beginning
//				if( MusicTypeTree.dataDescriptor.hasChildren(node) ) {
//					p = node;
//					r = 0;
//				} else {
//					p = node.parent();
//				}
//				// taking all of the items in the DragSouce, insert them into the 
//				// tree using parent p. 
//				for(var i:Number=0; i < items.length; i++) {
//					var insert:XML = <node />;
//					insert.@foddersortName= items[i];
//					//insert.@type = "restaurant";
//					MusicTypeTree.dataDescriptor.addChildAt(p, insert, r+i);
//				}
			}


			protected function MusicTypeTree_dragCompleteHandler(event:DragEvent):void
			{
				MusicTypeTree.selectedIndex = -1;

			}

		]]>
	</fx:Script>
	<fx:Declarations>
		<!-- 将非可视元素(例如服务、值对象)放在此处 -->
		<s:HTTPService  id="SrvTreeList" url="data/tree.xml" result="treeService_resultHandler(event)" useProxy="false"  resultFormat="xml" />
	</fx:Declarations>
	<!--@label这个非常重要,指定要显示的标题为XML重的label属性值。记住要显示树,httpService的send方法要在组件创建完成后被调用-->
	<mx:Tree click="tree1_clickHandler(event)" id="MusicTypeTree"
			 left="5" right="845" 
			 showRoot="false" 
			 labelField="@foddersortName"         
			 bottom="243" top="40"
			 dragEnabled="true"
			 dropEnabled="true"
			 allowMultipleSelection="true"
			 allowDragSelection="true"
			 dragDrop="MusicTypeTree_dragDropHandler(event)"
		     dragEnter="MusicTypeTree_dragEnterHandler(event)"
			 ></mx:Tree>
	<s:TextInput id="nextName" x="432" y="40"/>
	<s:Button x="443" y="82" label="增加为哥" click="addBefore()"/>
	<s:Button x="443" y="111" label="增加为弟" click="addAfter()"/>
	<s:Button x="444" y="144" click="addSon()" label="增加为孩子"/>
	<s:Button x="444" y="178" click="editNode()" label="修改节点"/>
	<s:Button x="444" y="211" click="deleteNode()" label="删除节点"/>
	<s:Button x="443" y="244" click="selectNode()" label="选择节点"/>
	<s:Button x="443" y="277" click="closeAll()" label="全部收缩"/>
	<s:Button x="443" y="306" click="openAll()" label="全部展开"/>
	
</s:Application>

 

Flex4之Tree开发_第3张图片

 

 

这次要说的是Flex的树组件的拖动效果,从树组件拖动到其他组件如List,DataGrid或者从其他组件拖动到Tree组件中,其实主要就是处理drag相关事件

 

 

 

第一:从Tree到List

 

   示例一

 

   

 

Xml代码
  1. <spanstyle="font-size: medium;"><?xmlversion="1.0"encoding="utf-8"?> 
  2. <s:Applicationxmlns:fx="http://ns.adobe.com/mxml/2009"  
  3.                xmlns:s="library://ns.adobe.com/flex/spark"  
  4.                xmlns:mx="library://ns.adobe.com/flex/mx"minWidth="955"minHeight="600"> 
  5.     <fx:Declarations> 
  6.         <!-- 将非可视元素(例如服务、值对象)放在此处 --> 
  7.         <fx:XMLid="myData"> 
  8.             <data> 
  9.                 <itemlabel="ActionScript"> 
  10.                     <itemlabel="Flash"/> 
  11.                     <itemlabel="Flex"/> 
  12.                 </item> 
  13.                 <itemlabel="Mirage"> 
  14.                 </item> 
  15.                 <itemlabel="JavaScript"/> 
  16.             </data> 
  17.         </fx:XML> 
  18.         <fx:XMLid="copyData"> 
  19.             <data> 
  20.                 <itemlabel="JavaScript"/> 
  21.             </data> 
  22.         </fx:XML> 
  23.     </fx:Declarations> 
  24.      
  25.     <fx:Script> 
  26.         <![CDATA[
  27.             import mx.controls.Button;
  28.             import mx.core.IUIComponent;
  29.             import mx.core.DragSource;
  30.             import mx.managers.DragManager;
  31.             import mx.events.DragEvent;
  32.             import mx.collections.ArrayCollection;
  33.             import mx.controls.Alert;
  34.             //拖动对象进入时
  35.             private function onDragOver( event:DragEvent ) : void
  36.             {
  37.                 var dropTarget:Tree = Tree(event.currentTarget);
  38.                 var r:int = dropTarget.calculateDropIndex(event);
  39.                 lbl.text = '当前位置:'+r.toString();//哪一个节点在鼠标下并给出相应信息
  40.                 tree2.selectedIndex = r; //显示位置
  41.                 var node:XML = sourceTree.selectedItem as XML;
  42.                 lbl2.text = '当前的拖动对象是:'+node.@label;//拖动对象的名字
  43.                 if( node.@label == "ActionScript" ) {
  44.                     DragManager.showFeedback(DragManager.NONE);
  45.                     return;
  46.                 }
  47.                 // 键盘控制
  48.                 if (event.ctrlKey)
  49.                     DragManager.showFeedback(DragManager.COPY);//复制
  50.                 else if (event.shiftKey)
  51.                     DragManager.showFeedback(DragManager.LINK);//剪切
  52.                 else {
  53.                     DragManager.showFeedback(DragManager.MOVE);//移动
  54.                 }
  55.             }
  56.            
  57.             //拖动对象被抛出后
  58.             private function onDragDrop( event:DragEvent ) : void
  59.             {
  60.                 // var ds:DragSource = event.dragSource;
  61.                 var dropTarget:Tree = Tree(event.currentTarget);
  62.                 // retrieve the data associated with the "items" format.
  63.                 //var items:Array = ds.dataForFormat("items") as Array;
  64.                 var r:int = tree2.calculateDropIndex(event);
  65.                 tree2.selectedIndex = r;//当拖放完成后选定相应的节点
  66.                 var node:XML = tree2.selectedItem as XML;
  67.                 var p:*;
  68.                 //tree2.dataDescriptor.hasChildren(node)判断有没有子节点,如果有就返回true
  69.                 if( tree2.dataDescriptor.hasChildren(node) ) {
  70.                     p = node;
  71.                     r = 0;
  72.                     trace('有子节点');
  73.                 } else {
  74.                     p = node.parent();
  75.                     trace('没有子节点');
  76.                 }
  77.                
  78.                 // taking all of the items in the DragSouce, insert them into the
  79.                 // tree using parent p.
  80.                 //       for(var i:Number=0; i < items.length; i++) {
  81.                 //             var insert:XML = <node/>;
  82.                 //             insert.@label = items[i];
  83.                 //             insert.@type = "restaurant";
  84.                 //             tree2.dataDescriptor.addChildAt(p, insert, r+i);
  85.                 //       }
  86.             }
  87.            
  88.             private function onDragComplete(event:DragEvent) : void
  89.             {
  90.                 trace('stop');
  91.                 tree2.selectedIndex = 0;
  92.             }
  93.         ]]> 
  94.     </fx:Script> 
  95.  
  96.      
  97.     <mx:Labeltext="Label"id="lbl"x="439"y="120"/> 
  98.     <mx:TreedropEnabled="true"dragEnabled="true"allowMultipleSelection="true"id="sourceTree" 
  99.              dataProvider="{myData.item}"labelField="@label"x="114"y="146"/> 
  100.      
  101.     <mx:TreedropEnabled="true"id="tree2"dataProvider="{copyData.item}"labelField="@label" 
  102.              dragOver="onDragOver(event)"dragDrop="onDragDrop(event)"dragComplete="onDragComplete(event)"x="382"y="146"/> 
  103.      
  104.     <mx:Labelx="382"y="94"text="Label"width="274"id="lbl2"height="29"/> 
  105.     <mx:Labelx="218"y="62"text="Tree与Tree之间的拖动"width="139"height="19"/> 
  106. </s:Application> 
  107. </span> 

 

<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" 
			   xmlns:s="library://ns.adobe.com/flex/spark" 
			   xmlns:mx="library://ns.adobe.com/flex/mx" minWidth="955" minHeight="600">
	<fx:Declarations>
		<!-- 将非可视元素(例如服务、值对象)放在此处 -->
		<fx:XML id="myData">
			<data>
				<item label="ActionScript">
					<item label="Flash" />
					<item label="Flex" />
				</item>
				<item label="Mirage">
				</item>
				<item label="JavaScript"/>
			</data>
		</fx:XML>
		<fx:XML id="copyData">
			<data>
				<item label="JavaScript"/>
			</data>
		</fx:XML>
	</fx:Declarations>
	
	<fx:Script>
		<![CDATA[
			import mx.controls.Button;
			import mx.core.IUIComponent;
			import mx.core.DragSource;
			import mx.managers.DragManager;
			import mx.events.DragEvent;
			import mx.collections.ArrayCollection;
			import mx.controls.Alert;
			//拖动对象进入时
			private function onDragOver( event:DragEvent ) : void
			{
				var dropTarget:Tree = Tree(event.currentTarget);
				var r:int = dropTarget.calculateDropIndex(event);
				lbl.text = '当前位置:'+r.toString();//哪一个节点在鼠标下并给出相应信息
				tree2.selectedIndex = r; //显示位置
				var node:XML = sourceTree.selectedItem as XML;
				lbl2.text = '当前的拖动对象是:'+node.@label;//拖动对象的名字
				if( node.@label == "ActionScript" ) {
					DragManager.showFeedback(DragManager.NONE);
					return;
				}
				// 键盘控制 
				if (event.ctrlKey)
					DragManager.showFeedback(DragManager.COPY);//复制
				else if (event.shiftKey)
					DragManager.showFeedback(DragManager.LINK);//剪切
				else {
					DragManager.showFeedback(DragManager.MOVE);//移动
				}
			} 
			
			//拖动对象被抛出后
			private function onDragDrop( event:DragEvent ) : void
			{
				// var ds:DragSource = event.dragSource;
				var dropTarget:Tree = Tree(event.currentTarget);
				// retrieve the data associated with the "items" format.
				//var items:Array = ds.dataForFormat("items") as Array;
				var r:int = tree2.calculateDropIndex(event);
				tree2.selectedIndex = r;//当拖放完成后选定相应的节点
				var node:XML = tree2.selectedItem as XML;
				var p:*;
				//tree2.dataDescriptor.hasChildren(node)判断有没有子节点,如果有就返回true
				if( tree2.dataDescriptor.hasChildren(node) ) {
					p = node;
					r = 0;
					trace('有子节点');
				} else {
					p = node.parent();
					trace('没有子节点');
				}
				
				// taking all of the items in the DragSouce, insert them into the 
				// tree using parent p. 
				//       for(var i:Number=0; i < items.length; i++) {
				//             var insert:XML = <node/>;
				//             insert.@label = items[i];
				//             insert.@type = "restaurant";
				//             tree2.dataDescriptor.addChildAt(p, insert, r+i);
				//       }
			} 
			
			private function onDragComplete(event:DragEvent) : void
			{
				trace('stop');
				tree2.selectedIndex = 0;
			}

		]]>
	</fx:Script>

	
	<mx:Label text="Label" id="lbl" x="439" y="120"/>
	<mx:Tree dropEnabled="true" dragEnabled="true" allowMultipleSelection="true" id="sourceTree"
			 dataProvider="{myData.item}" labelField="@label" x="114" y="146"/>
	
	<mx:Tree dropEnabled="true" id="tree2" dataProvider="{copyData.item}" labelField="@label"
			 dragOver="onDragOver(event)" dragDrop="onDragDrop(event)" dragComplete="onDragComplete(event)" x="382" y="146"/>
	
	<mx:Label x="382" y="94" text="Label" width="274" id="lbl2" height="29"/>
	<mx:Label x="218" y="62" text="Tree与Tree之间的拖动" width="139" height="19"/>
</s:Application>

 

   Flex4之Tree开发_第4张图片

 

  

 

   示例二

 

 

 

Xml代码
  1. <spanstyle="font-size: medium;"><?xmlversion="1.0"encoding="utf-8"?> 
  2. <s:Applicationxmlns:fx="http://ns.adobe.com/mxml/2009"  
  3.                xmlns:s="library://ns.adobe.com/flex/spark"  
  4.                xmlns:mx="library://ns.adobe.com/flex/mx"minWidth="955"minHeight="600"> 
  5.     <fx:Declarations> 
  6.         <!-- 将非可视元素(例如服务、值对象)放在此处 --> 
  7.         <!-- 这里定义班组树的结构和内容 --> 
  8.         <fx:XMLListid="treeData"> 
  9.             <nodelabel="Mail Box"> 
  10.                 <nodelabel="工区1"> 
  11.                     <nodelabel="工地1"> 
  12.                         <nodelabel="班组1.1"data="111"/> 
  13.                         <nodelabel="班组1.2"/> 
  14.                     </node> 
  15.                     <nodelabel="工地2"> 
  16.                         <nodelabel="班组2.1"/> 
  17.                         <nodelabel="班组2.2"/> 
  18.                     </node> 
  19.                     <nodelabel="工地3"> 
  20.                         <nodelabel="班组3.1"/> 
  21.                         <nodelabel="班组3.2"/> 
  22.                     </node> 
  23.                 </node> 
  24.                 <nodelabel="工区2"> 
  25.                     <nodelabel="Professional"/> 
  26.                     <nodelabel="Personal"/> 
  27.                 </node> 
  28.             </node>     
  29.         </fx:XMLList>     
  30.     </fx:Declarations> 
  31.      
  32.      
  33.     <fx:Script> 
  34.         <![CDATA[
  35.             import mx.controls.Label;
  36.             import mx.core.IUIComponent;
  37.             import mx.core.DragSource;
  38.             import mx.managers.DragManager;
  39.             import mx.events.DragEvent;
  40.             import mx.collections.ArrayCollection;
  41.             import mx.controls.Alert;
  42.            
  43.             [Bindable]
  44.             public var list:ArrayCollection=new ArrayCollection();
  45.            
  46.             //拖动初始器
  47.             private function dragSource(e:MouseEvent,format:String):void
  48.             {
  49.                 var iu:IUIComponent = e.currentTarget as IUIComponent;
  50.                 var ds:DragSource=new DragSource();
  51.                 ds.addData(myTree.selectedItem,format);//为myTree设置一个标号forma
  52.                 var lbl:Label=new Label();
  53.                 lbl.text="开始拖动";
  54.                 lbl.x = e.stageX;
  55.                 lbl.y = e.stageY;
  56.                 //lbl拖动的影子,默认为自己doDrag(拖动的对象,拖动器,事件,拖动影子,x,y)
  57.                 DragManager.doDrag(iu,ds,e,lbl,e.stageX,e.stageY);//开始拖动这个物体           
  58.             }
  59.            
  60.             //当拖进去时
  61.             private function doDragEnter(e:DragEvent,format:String):void
  62.             {
  63.                 var len:int=(mylist.dataProvider as ArrayCollection).length;//判断list中有多少个数据
  64.                 var selectnode:XML = myTree.selectedItem as XML;//选择的节点名
  65.                 for(var i:int=0;i<len;i++)
  66.                 {
  67.                     if(validateIsEqual((mylist.dataProvider as ArrayCollection).getItemAt(i),selectnode))
  68.                     {
  69.                         Alert.show("该班组已经存在!");
  70.                     }
  71.                 }
  72.                 if(e.dragSource.hasFormat(format)){//如果标号为format则接受拖来的物体
  73.                     DragManager.acceptDragDrop(IUIComponent(e.target));
  74.                 }
  75.             }
  76.            
  77.             //当拖完成时
  78.             private function onDragDrop(e:DragEvent,format:String):void{
  79.                 var row:Object=e.dragSource.dataForFormat(format);
  80.                 list.addItem(row);//list的数据源添加数据
  81.             }
  82.            
  83.             //判断选中的节点是否和List中的内容一样
  84.             private function validateIsEqual(obj1:Object,obj2:Object):Boolean
  85.             {
  86.                 if(obj1==obj2)//条件未判断
  87.                 {
  88.                     return true;
  89.                 }
  90.                 else
  91.                 {
  92.                     return false;
  93.                 }
  94.             }
  95.         ]]> 
  96.     </fx:Script> 
  97.     <mx:Treeid="myTree"labelField="@label"dragEnabled="true"mouseDown="dragSource(event,'stringFormat')"  
  98.              showRoot="true"dataProvider="{treeData}"   height="331"horizontalCenter="-120"verticalCenter="7"width="190"/> 
  99.      
  100.     <mx:Listheight="331"labelField="@label"dragEnter="doDragEnter(event,'stringFormat')" 
  101.              dataProvider="{list}"dragDrop="onDragDrop(event,'stringFormat')"width="162"id="mylist"horizontalCenter="114"verticalCenter="7"></mx:List> 
  102.     <mx:Labelx="282.5"y="97"text="Tree与list的拖动"width="152"/> 
  103. </s:Application> 
  104. </span> 

 

<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" 
			   xmlns:s="library://ns.adobe.com/flex/spark" 
			   xmlns:mx="library://ns.adobe.com/flex/mx" minWidth="955" minHeight="600">
	<fx:Declarations>
		<!-- 将非可视元素(例如服务、值对象)放在此处 -->
		<!-- 这里定义班组树的结构和内容 -->
		<fx:XMLList id="treeData">
			<node label="Mail Box">
				<node label="工区1">
					<node label="工地1">
						<node label="班组1.1" data="111"/>
						<node label="班组1.2"/>
					</node>
					<node label="工地2">
						<node label="班组2.1"/>
						<node label="班组2.2"/>
					</node>
					<node label="工地3">
						<node label="班组3.1"/>
						<node label="班组3.2"/>
					</node>
				</node>
				<node label="工区2">
					<node label="Professional"/>
					<node label="Personal"/>
				</node>
			</node>    
		</fx:XMLList>    
	</fx:Declarations>
	
	
	<fx:Script>
		<![CDATA[
			import mx.controls.Label;
			import mx.core.IUIComponent;
			import mx.core.DragSource;
			import mx.managers.DragManager;
			import mx.events.DragEvent;
			import mx.collections.ArrayCollection;
			import mx.controls.Alert;
			
			[Bindable]
			public var list:ArrayCollection=new ArrayCollection();
			
			//拖动初始器
			private function dragSource(e:MouseEvent,format:String):void
			{
				var iu:IUIComponent = e.currentTarget as IUIComponent;
				var ds:DragSource=new DragSource();
				ds.addData(myTree.selectedItem,format);//为myTree设置一个标号forma
				var lbl:Label=new Label(); 
				lbl.text="开始拖动";
				lbl.x = e.stageX;
				lbl.y = e.stageY;
				//lbl拖动的影子,默认为自己doDrag(拖动的对象,拖动器,事件,拖动影子,x,y)
				DragManager.doDrag(iu,ds,e,lbl,e.stageX,e.stageY);//开始拖动这个物体            
			}
			
			//当拖进去时
			private function doDragEnter(e:DragEvent,format:String):void
			{
				var len:int=(mylist.dataProvider as ArrayCollection).length;//判断list中有多少个数据
				var selectnode:XML = myTree.selectedItem as XML;//选择的节点名
				for(var i:int=0;i<len;i++)
				{
					if(validateIsEqual((mylist.dataProvider as ArrayCollection).getItemAt(i),selectnode))
					{
						Alert.show("该班组已经存在!");
					}
				}
				if(e.dragSource.hasFormat(format)){//如果标号为format则接受拖来的物体
					DragManager.acceptDragDrop(IUIComponent(e.target));
				}
			}
			
			//当拖完成时
			private function onDragDrop(e:DragEvent,format:String):void{
				var row:Object=e.dragSource.dataForFormat(format);
				list.addItem(row);//list的数据源添加数据
			}
			
			//判断选中的节点是否和List中的内容一样
			private function validateIsEqual(obj1:Object,obj2:Object):Boolean
			{
				if(obj1==obj2)//条件未判断
				{
					return true;
				}
				else
				{
					return false;
				}
			}
		]]>
	</fx:Script>
	<mx:Tree id="myTree" labelField="@label" dragEnabled="true" mouseDown="dragSource(event,'stringFormat')" 
			 showRoot="true" dataProvider="{treeData}"   height="331" horizontalCenter="-120" verticalCenter="7" width="190"/>
	
	<mx:List height="331" labelField="@label" dragEnter="doDragEnter(event,'stringFormat')"
			 dataProvider="{list}" dragDrop="onDragDrop(event,'stringFormat')" width="162" id="mylist" horizontalCenter="114" verticalCenter="7"></mx:List>
	<mx:Label x="282.5" y="97" text="Tree与list的拖动" width="152"/>
</s:Application>

 

 

 

   Flex4之Tree开发_第5张图片

 

第二:从Tree到DataGrid

 

 

 

Xml代码
  1. <spanstyle="font-size: medium;"><?xmlversion="1.0"encoding="utf-8"?> 
  2. <s:Applicationxmlns:fx="http://ns.adobe.com/mxml/2009"  
  3.                xmlns:s="library://ns.adobe.com/flex/spark"  
  4.                xmlns:mx="library://ns.adobe.com/flex/mx"minWidth="955"minHeight="600"> 
  5.     <s:layout> 
  6.         <s:BasicLayout/> 
  7.     </s:layout> 
  8.     <fx:Declarations> 
  9.         <!-- 将非可视元素(例如服务、值对象)放在此处 --> 
  10.         <fx:XMLid="treeData"xmlns=""> 
  11.             <root> 
  12.                  
  13.                 <nodelabel="Massachusetts"type="state"data="MA"> 
  14.                     <nodelabel="Boston"type="city"> 
  15.                         <nodelabel="Smoke House Grill"type="restaurant"/> 
  16.                         <nodelabel="Equator"type="restaurant"/> 
  17.                         <nodelabel="Aquataine"type="restaurant"/> 
  18.                         <nodelabel="Grill 23"type="restaurant"/> 
  19.                          
  20.                     </node> 
  21.                     <nodelabel="Provincetown"type="city"> 
  22.                         <nodelabel="Lobster Pot"type="restaurant"/> 
  23.                         <nodelabel="The Mews"type="restaurant"/> 
  24.                     </node> 
  25.                 </node> 
  26.                  
  27.                 <nodelabel="California"type="state"data="CA"> 
  28.                     <nodelabel="San Francisco"type="city"> 
  29.                         <nodelabel="Frog Lane"type="restaurant"/> 
  30.                     </node> 
  31.                 </node> 
  32.             </root> 
  33.              
  34.         </fx:XML> 
  35.     </fx:Declarations> 
  36.     <fx:Script> 
  37.         <![CDATA[
  38.         import mx.controls.Alert;
  39.         import mx.controls.Label;
  40.         import mx.controls.List;
  41.         import mx.collections.ArrayCollection;
  42.         import mx.core.DragSource;
  43.         import mx.controls.Tree;
  44.         import mx.controls.DataGrid;
  45.         import mx.controls.listClasses.ListBase;
  46.         import mx.events.DragEvent;
  47.         import mx.containers.Canvas;
  48.         import mx.managers.DragManager;
  49.         import mx.core.UIComponent;
  50.        
  51.         [Bindable]
  52.        
  53.         private var dataGridProvider:ArrayCollection = new ArrayCollection();
  54.         /**
  55.         * Handles the dragEnter event on the DataGrid control.
  56.         * If the dragInitiator is the Tree control, then only nodes of type "restaurant"
  57.         * are permitted to be dropped.
  58.         * Here you can see that by examining the dragSource you can determine if
  59.         * the control should accept the drop. The DataGrid control would not
  60.         * know how to treat a branch+children from the Tree control, so only leaf (restaurant)
  61.         * nodes are accepted.
  62.         */
  63.        
  64.         private function onDragEnter( event:DragEvent ) : void
  65.        
  66.         {           
  67.         if( event.dragInitiator is Tree ) {
  68.         var ds:DragSource = event.dragSource;
  69.         if( !ds.hasFormat("treeItems") ) return;     // no useful data
  70.        
  71.         var items:Array = ds.dataForFormat("treeItems") as Array;
  72.         for(var i:Number=0; i < items.length; i++) {
  73.        
  74.         var item:XML = XML(items[i]);
  75.         if( item.@type != "restaurant" ) return; // not what we want
  76.        
  77.         }
  78.         }
  79.         // If the Tree control passes or the dragInitiator is not a Tree control,
  80.         // accept the drop.
  81.         DragManager.acceptDragDrop(UIComponent(event.currentTarget));
  82.         }       
  83.         /**
  84.         * Handles the dragOver event on the DataGrid control.
  85.         * If the dragInitiator is the Tree control, only copy is allowed. Otherwise, a move
  86.         * or link can take place from the List control.
  87.         */
  88.        
  89.         private function onDragOver( event:DragEvent ) : void
  90.        
  91.         {
  92.         if( event.dragInitiator is Tree ) {
  93.         DragManager.showFeedback(DragManager.COPY);
  94.         } else {
  95.        
  96.         if (event.ctrlKey)
  97.         DragManager.showFeedback(DragManager.COPY);
  98.         else if (event.shiftKey)
  99.        
  100.         DragManager.showFeedback(DragManager.LINK);
  101.         else {
  102.         DragManager.showFeedback(DragManager.MOVE);
  103.         }
  104.        
  105.         }
  106.         }       
  107.         /**
  108.         * Handles the dragExit event on the drop target and just hides the
  109.         * the drop feedback.
  110.         */
  111.         private function onDragExit( event:DragEvent ) : void
  112.        
  113.         {
  114.         var dropTarget:ListBase=ListBase(event.currentTarget);  
  115.         dropTarget.hideDropFeedback(event);
  116.         }
  117.        
  118.         /**
  119.         * Handles the dragDrop event on the DataGrid when the
  120.         * drag proxy is released.
  121.         */
  122.         private function onGridDragDrop( event:DragEvent ) : void
  123.        
  124.         {
  125.         var ds:DragSource = event.dragSource;
  126.         var dropTarget:DataGrid = DataGrid(event.currentTarget);
  127.         var arr:Array;
  128.         if( ds.hasFormat("items") ) {
  129.        
  130.         arr = ds.dataForFormat("items") as Array;
  131.         } else if( ds.hasFormat("treeItems") ) {
  132.        
  133.         arr = ds.dataForFormat("treeItems") as Array;
  134.         }
  135.         for(var i:Number=0; i < arr.length; i++) {
  136.        
  137.         var node:XML = XML(arr[i]);
  138.         var item:Object = new Object();
  139.         item.label = node.@label;
  140.         item.type  = node.@type;
  141.         dataGridProvider.addItem(item);
  142.         }
  143.        
  144.         onDragExit(event);
  145.         }
  146.         /**
  147.         * Intercepts the dragComplete event on the Tree control
  148.         * and prevents the default behavior from happening. This is necessary
  149.         * if the item being dragged from the Tree control is dropped on a non-Tree
  150.         * object, such as the DataGrid.
  151.         */
  152.         private function onTreeDragComplete(event:DragEvent):void {
  153.        
  154.         event.preventDefault();
  155.         }       
  156.         /**
  157.         * Selects all of the items in the List if Ctrl+A is picked when the List control
  158.         * has focus.
  159.         */
  160.         private function selectAllMaybe( event:KeyboardEvent ) : void
  161.        
  162.         {
  163.         if( event.ctrlKey && event.keyCode == 65 ) {
  164.        
  165.         var l:List = List(event.currentTarget);
  166.         var allItems:Array = new Array(l.dataProvider.length);
  167.         for(var i:Number=0; i < allItems.length; i++) {
  168.        
  169.         allItems[i] = i;
  170.         }
  171.         l.selectedIndices = allItems;
  172.         }
  173.        
  174.         }
  175.         ]]> 
  176.     </fx:Script> 
  177.     <mx:Labelx="34"y="40"text="Drag items from this Tree"/> 
  178.     <mx:Labelx="34"y="55"text="(items are copied)"/> 
  179.      
  180.     <mx:Treex="34"y="81"width="181"height="189" 
  181.              dataProvider="{treeData.node}" 
  182.              labelField="@label" 
  183.              dropEnabled="false" 
  184.              dragEnabled="true" 
  185.              dragComplete="onTreeDragComplete(event)" 
  186.              dragMoveEnabled="false" 
  187.              /> 
  188.      
  189.     <mx:Labelx="291"y="55"text="Drop items from Tree here"/> 
  190.     <mx:DataGridx="291"y="81"height="189" 
  191.                  dragEnabled="true" 
  192.                  dataProvider="{dataGridProvider}" 
  193.                  dragEnter="onDragEnter(event)" 
  194.                  dragOver="onDragOver(event)" 
  195.                  dragDrop="onGridDragDrop(event)" 
  196.                  dragExit="onDragExit(event)"> 
  197.          
  198.         <mx:columns> 
  199.             <mx:DataGridColumnheaderText="Label"dataField="label"/> 
  200.             <mx:DataGridColumnheaderText="Type"dataField="type"/> 
  201.              
  202.         </mx:columns> 
  203.     </mx:DataGrid> 
  204.      
  205. </s:Application> 
  206. </span> 

 

<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" 
			   xmlns:s="library://ns.adobe.com/flex/spark" 
			   xmlns:mx="library://ns.adobe.com/flex/mx" minWidth="955" minHeight="600">
	<s:layout>
		<s:BasicLayout/>
	</s:layout>
	<fx:Declarations>
		<!-- 将非可视元素(例如服务、值对象)放在此处 -->
		<fx:XML id="treeData" xmlns="">
			<root>
				
				<node label="Massachusetts" type="state" data="MA">
					<node label="Boston" type="city" >
						<node label="Smoke House Grill" type="restaurant" />
						<node label="Equator" type="restaurant" />
						<node label="Aquataine" type="restaurant" />
						<node label="Grill 23" type="restaurant" />
						
					</node>
					<node label="Provincetown" type="city" >
						<node label="Lobster Pot" type="restaurant" />
						<node label="The Mews" type="restaurant" />
					</node>
				</node>
				
				<node label="California" type="state" data="CA">
					<node label="San Francisco" type="city" >
						<node label="Frog Lane" type="restaurant" />
					</node>
				</node>
			</root>
			
		</fx:XML>
	</fx:Declarations>
	<fx:Script>
		<![CDATA[
		import mx.controls.Alert;
		import mx.controls.Label;
		import mx.controls.List;
		import mx.collections.ArrayCollection;
		import mx.core.DragSource;
		import mx.controls.Tree;
		import mx.controls.DataGrid;
		import mx.controls.listClasses.ListBase;
		import mx.events.DragEvent;
		import mx.containers.Canvas;
		import mx.managers.DragManager;
		import mx.core.UIComponent;
		
		[Bindable]
		
		private var dataGridProvider:ArrayCollection = new ArrayCollection();
		/**
		* Handles the dragEnter event on the DataGrid control.
		* If the dragInitiator is the Tree control, then only nodes of type "restaurant"
		* are permitted to be dropped.
		* Here you can see that by examining the dragSource you can determine if
		* the control should accept the drop. The DataGrid control would not
		* know how to treat a branch+children from the Tree control, so only leaf (restaurant)
		* nodes are accepted.
		*/
		
		private function onDragEnter( event:DragEvent ) : void
		
		{            
		if( event.dragInitiator is Tree ) {
		var ds:DragSource = event.dragSource;
		if( !ds.hasFormat("treeItems") ) return;     // no useful data
		
		var items:Array = ds.dataForFormat("treeItems") as Array;
		for(var i:Number=0; i < items.length; i++) {
		
		var item:XML = XML(items[i]);
		if( item.@type != "restaurant" ) return; // not what we want
		
		}
		} 
		// If the Tree control passes or the dragInitiator is not a Tree control,
		// accept the drop.
		DragManager.acceptDragDrop(UIComponent(event.currentTarget)); 
		}        
		/**
		* Handles the dragOver event on the DataGrid control.
		* If the dragInitiator is the Tree control, only copy is allowed. Otherwise, a move
		* or link can take place from the List control.
		*/
		
		private function onDragOver( event:DragEvent ) : void
		
		{
		if( event.dragInitiator is Tree ) {
		DragManager.showFeedback(DragManager.COPY);
		} else {
		
		if (event.ctrlKey)
		DragManager.showFeedback(DragManager.COPY);
		else if (event.shiftKey)
		
		DragManager.showFeedback(DragManager.LINK);
		else {
		DragManager.showFeedback(DragManager.MOVE);
		}
		
		}
		}        
		/**
		* Handles the dragExit event on the drop target and just hides the 
		* the drop feedback.
		*/
		private function onDragExit( event:DragEvent ) : void
		
		{
		var dropTarget:ListBase=ListBase(event.currentTarget);   
		dropTarget.hideDropFeedback(event);
		}
		
		/**
		* Handles the dragDrop event on the DataGrid when the 
		* drag proxy is released. 
		*/
		private function onGridDragDrop( event:DragEvent ) : void
		
		{
		var ds:DragSource = event.dragSource;
		var dropTarget:DataGrid = DataGrid(event.currentTarget);
		var arr:Array;
		if( ds.hasFormat("items") ) {
		
		arr = ds.dataForFormat("items") as Array;
		} else if( ds.hasFormat("treeItems") ) {
		
		arr = ds.dataForFormat("treeItems") as Array;
		}
		for(var i:Number=0; i < arr.length; i++) {
		
		var node:XML = XML(arr[i]);
		var item:Object = new Object();
		item.label = node.@label;
		item.type  = node.@type;
		dataGridProvider.addItem(item);
		}
		
		onDragExit(event); 
		}
		/**
		* Intercepts the dragComplete event on the Tree control
		* and prevents the default behavior from happening. This is necessary
		* if the item being dragged from the Tree control is dropped on a non-Tree
		* object, such as the DataGrid.
		*/
		private function onTreeDragComplete(event:DragEvent):void {
		
		event.preventDefault();
		}        
		/**
		* Selects all of the items in the List if Ctrl+A is picked when the List control
		* has focus.
		*/
		private function selectAllMaybe( event:KeyboardEvent ) : void
		
		{
		if( event.ctrlKey && event.keyCode == 65 ) {
		
		var l:List = List(event.currentTarget);
		var allItems:Array = new Array(l.dataProvider.length);
		for(var i:Number=0; i < allItems.length; i++) {
		
		allItems[i] = i;
		}
		l.selectedIndices = allItems;
		}
		
		}
		]]>
	</fx:Script>
	<mx:Label x="34" y="40" text="Drag items from this Tree"/>
	<mx:Label x="34" y="55" text="(items are copied)"/>
	
	<mx:Tree x="34" y="81" width="181" height="189"
			 dataProvider="{treeData.node}"
			 labelField="@label"
			 dropEnabled="false"
			 dragEnabled="true"
			 dragComplete="onTreeDragComplete(event)"
			 dragMoveEnabled="false"
			 />
	
	<mx:Label x="291" y="55" text="Drop items from Tree here"/>
	<mx:DataGrid x="291" y="81" height="189"
				 dragEnabled="true"
				 dataProvider="{dataGridProvider}"
				 dragEnter="onDragEnter(event)"
				 dragOver="onDragOver(event)"
				 dragDrop="onGridDragDrop(event)"
				 dragExit="onDragExit(event)">
		
		<mx:columns>
			<mx:DataGridColumn headerText="Label" dataField="label"/>
			<mx:DataGridColumn headerText="Type" dataField="type"/>
			
		</mx:columns>
	</mx:DataGrid>
	
</s:Application>

 

Flex4之Tree开发_第6张图片

 

 

 

 

 

第三:从List到Tree

 

   

 

Xml代码
  1. <spanstyle="font-size: medium;"><?xmlversion="1.0"encoding="utf-8"?> 
  2. <s:Applicationxmlns:fx="http://ns.adobe.com/mxml/2009"  
  3.                xmlns:s="library://ns.adobe.com/flex/spark"  
  4.                xmlns:mx="library://ns.adobe.com/flex/mx"minWidth="955"minHeight="600"> 
  5.     <s:layout> 
  6.         <s:BasicLayout/> 
  7.     </s:layout> 
  8.     <fx:Declarations> 
  9.         <!-- 将非可视元素(例如服务、值对象)放在此处 --> 
  10.         <fx:XMLid="treeData"xmlns=""> 
  11.              
  12.             <root> 
  13.                 <nodelabel="Massachusetts"type="state"data="MA"> 
  14.                     <nodelabel="Boston"type="city"> 
  15.                         <nodelabel="Smoke House Grill"type="restaurant"/> 
  16.                         <nodelabel="Equator"type="restaurant"/> 
  17.                         <nodelabel="Aquataine"type="restaurant"/> 
  18.                          
  19.                         <nodelabel="Grill 23"type="restaurant"/> 
  20.                     </node> 
  21.                     <nodelabel="Provincetown"type="city"> 
  22.                         <nodelabel="Lobster Pot"type="restaurant"/> 
  23.                         <nodelabel="The Mews"type="restaurant"/> 
  24.                     </node> 
  25.                      
  26.                 </node> 
  27.                 <nodelabel="California"type="state"data="CA"> 
  28.                     <nodelabel="San Francisco"type="city"> 
  29.                         <nodelabel="Frog Lane"type="restaurant"/> 
  30.                     </node> 
  31.                 </node> 
  32.                  
  33.             </root> 
  34.         </fx:XML>     
  35.         <fx:Arrayid="listData"> 
  36.              
  37.             <fx:String>Johnny Rocket's</fx:String> 
  38.              
  39.             <fx:String>Jet Pizza</fx:String> 
  40.             <fx:String>Steve's Greek</fx:String> 
  41.             <fx:String>Sonsie</fx:String> 
  42.             <fx:String>The Border Cafe</fx:String> 
  43.              
  44.         </fx:Array> 
  45.     </fx:Declarations> 
  46.     <fx:Script> 
  47.         <![CDATA[
  48.             import mx.events.DragEvent;
  49.             import mx.managers.DragManager;
  50.             import mx.core.DragSource;
  51.             import mx.core.UIComponent;
  52.             import mx.controls.Tree;
  53.             /**
  54.              * Called as soon as the dragProxy enters the target. You can add logic
  55.              * to determine if the target will accept the drop based on the
  56.              * dragInitiator, the data available in the dragSource.
  57.              * Here the drop is blindly accepted.
  58.              */
  59.            
  60.             private function onDragEnter( event:DragEvent ) : void
  61.                
  62.             {
  63.                 DragManager.acceptDragDrop(UIComponent(event.currentTarget));
  64.             }
  65.             /**
  66.              * Called while the dragProxy is over the drop target. You can
  67.              * use this function to determine the type of feedback to show.
  68.              * Since the List is set to allow MOVE (the item is deleted
  69.              * once dropped), different feedback possibilities are given.
  70.              *
  71.              * Also, for this application, the Tree control node the dragProxy is
  72.              * over is selected. As the dragProxy moves, the Tree control's
  73.              * selection changes.
  74.              *
  75.              * For a bit more complication, the drop is being allowed
  76.              * only over nodes whose type is NOT 'state'.
  77.              * The feedback is removed.
  78.              */
  79.             private function onDragOver( event:DragEvent ) : void
  80.                
  81.             {
  82.                 var dropTarget:Tree = Tree(event.currentTarget);
  83.                 var r:int = dropTarget.calculateDropIndex(event);
  84.                 tree.selectedIndex = r;
  85.                 var node:XML = tree.selectedItem as XML;
  86.                 if( node.@type == "state" ) {
  87.                    
  88.                     DragManager.showFeedback(DragManager.NONE);
  89.                     return;
  90.                 }
  91.                 if (event.ctrlKey)
  92.                    
  93.                     DragManager.showFeedback(DragManager.COPY);
  94.                 else if (event.shiftKey)
  95.                     DragManager.showFeedback(DragManager.LINK);
  96.                 else {
  97.                    
  98.                     DragManager.showFeedback(DragManager.MOVE);
  99.                 }
  100.             }
  101.             /**
  102.              * Called when the dragProxy is released
  103.              * over the drop target. The information in the dragSource
  104.              * is extracted and processed.
  105.              *
  106.              * The target node is determined and
  107.              * all of the data selected (the List has allowMultipleSection
  108.              * set) is added.
  109.              */
  110.             private function onDragDrop( event:DragEvent ) : void
  111.                
  112.             {
  113.                 var ds:DragSource = event.dragSource;
  114.                 var dropTarget:Tree = Tree(event.currentTarget);
  115.                 var items:Array = ds.dataForFormat("items") as Array;
  116.                 var r:int = tree.calculateDropIndex(event);
  117.                 tree.selectedIndex = r;
  118.                 var node:XML = tree.selectedItem as XML;
  119.                 var p:*;
  120.                 // if the selected node has children (it is type==city),
  121.                
  122.                 // then add the items at the beginning
  123.                 if( tree.dataDescriptor.hasChildren(node) ) {
  124.                     p = node;
  125.                     r = 0;
  126.                 } else {
  127.                    
  128.                     p = node.parent();
  129.                 }
  130.                 for(var i:Number=0; i < items.length; i++) {
  131.                    
  132.                     var insert:XML = <node />;
  133.                     insert.@label = items[i];
  134.                     insert.@type  = "restaurant";
  135.                     tree.dataDescriptor.addChildAt(p, insert, r+i);
  136.                 }
  137.                
  138.             }
  139.             /**
  140.              * Called when the drag operation completes, whether
  141.              * successfully or not. The tree is cleared of its
  142.              * selection.
  143.              */
  144.             private function onDragComplete( event:DragEvent ) : void
  145.                
  146.             {
  147.                 tree.selectedIndex = -1;
  148.             }       
  149.         ]]> 
  150.     </fx:Script> 
  151.  
  152.     <mx:Panelx="48"y="125"width="447"height="351"layout="absolute"title="Drag onto Tree">     
  153.         <mx:Treewidth="186"left="10"top="10"bottom="10"id="tree" 
  154.                  labelField="@label" 
  155.                  dataProvider="{treeData.node}" 
  156.                  dropEnabled="false" 
  157.                  dragMoveEnabled="false" 
  158.                  dragEnter="onDragEnter(event)" 
  159.                  dragOver="onDragOver(event)" 
  160.                  dragDrop="onDragDrop(event)"> 
  161.              
  162.         </mx:Tree>         
  163.         <mx:Listwidth="188"height="206"right="10"bottom="10"id="list" 
  164.                  allowMultipleSelection="true" 
  165.                  dataProvider="{listData}" 
  166.                  dragEnabled="true" 
  167.                  dragMoveEnabled="true" 
  168.                  dragComplete="onDragComplete(event)"> 
  169.              
  170.         </mx:List>         
  171.         <mx:Textx="229"y="10"text="Drag from the list below to the tree"width="188"height="39"/> 
  172.          
  173.         <mx:Labelx="229"y="69"text="restaurants"/> 
  174.     </mx:Panel>     
  175. </s:Application> 
  176. </span> 

 

<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" 
			   xmlns:s="library://ns.adobe.com/flex/spark" 
			   xmlns:mx="library://ns.adobe.com/flex/mx" minWidth="955" minHeight="600">
	<s:layout>
		<s:BasicLayout/>
	</s:layout>
	<fx:Declarations>
		<!-- 将非可视元素(例如服务、值对象)放在此处 -->
		<fx:XML id="treeData" xmlns="">
			
			<root>
				<node label="Massachusetts" type="state" data="MA">
					<node label="Boston" type="city" >
						<node label="Smoke House Grill" type="restaurant" />
						<node label="Equator" type="restaurant" />
						<node label="Aquataine" type="restaurant" />
						
						<node label="Grill 23" type="restaurant" />
					</node>
					<node label="Provincetown" type="city" >
						<node label="Lobster Pot" type="restaurant" />
						<node label="The Mews" type="restaurant" />
					</node>
					
				</node>
				<node label="California" type="state" data="CA">
					<node label="San Francisco" type="city" >
						<node label="Frog Lane" type="restaurant" />
					</node>
				</node>
				
			</root>
		</fx:XML>    
		<fx:Array id="listData">
			
			<fx:String>Johnny Rocket's</fx:String>
			
			<fx:String>Jet Pizza</fx:String>
			<fx:String>Steve's Greek</fx:String>
			<fx:String>Sonsie</fx:String>
			<fx:String>The Border Cafe</fx:String>
			
		</fx:Array>
	</fx:Declarations>
	<fx:Script>
		<![CDATA[
			import mx.events.DragEvent;
			import mx.managers.DragManager;
			import mx.core.DragSource;
			import mx.core.UIComponent;
			import mx.controls.Tree;
			/**
			 * Called as soon as the dragProxy enters the target. You can add logic
			 * to determine if the target will accept the drop based on the
			 * dragInitiator, the data available in the dragSource.
			 * Here the drop is blindly accepted.
			 */
			
			private function onDragEnter( event:DragEvent ) : void
				
			{
				DragManager.acceptDragDrop(UIComponent(event.currentTarget));
			}
			/**
			 * Called while the dragProxy is over the drop target. You can
			 * use this function to determine the type of feedback to show.
			 * Since the List is set to allow MOVE (the item is deleted
			 * once dropped), different feedback possibilities are given.
			 *
			 * Also, for this application, the Tree control node the dragProxy is
			 * over is selected. As the dragProxy moves, the Tree control's
			 * selection changes.
			 *
			 * For a bit more complication, the drop is being allowed
			 * only over nodes whose type is NOT 'state'.
			 * The feedback is removed.
			 */
			private function onDragOver( event:DragEvent ) : void
				
			{
				var dropTarget:Tree = Tree(event.currentTarget);
				var r:int = dropTarget.calculateDropIndex(event);
				tree.selectedIndex = r;
				var node:XML = tree.selectedItem as XML;
				if( node.@type == "state" ) {
					
					DragManager.showFeedback(DragManager.NONE);
					return;
				}
				if (event.ctrlKey)
					
					DragManager.showFeedback(DragManager.COPY);
				else if (event.shiftKey)
					DragManager.showFeedback(DragManager.LINK);
				else {
					
					DragManager.showFeedback(DragManager.MOVE);
				}
			}
			/**
			 * Called when the dragProxy is released
			 * over the drop target. The information in the dragSource
			 * is extracted and processed.
			 *
			 * The target node is determined and 
			 * all of the data selected (the List has allowMultipleSection
			 * set) is added.
			 */
			private function onDragDrop( event:DragEvent ) : void
				
			{
				var ds:DragSource = event.dragSource;
				var dropTarget:Tree = Tree(event.currentTarget);
				var items:Array = ds.dataForFormat("items") as Array;
				var r:int = tree.calculateDropIndex(event);
				tree.selectedIndex = r;
				var node:XML = tree.selectedItem as XML;
				var p:*;
				// if the selected node has children (it is type==city),
				
				// then add the items at the beginning
				if( tree.dataDescriptor.hasChildren(node) ) {
					p = node;
					r = 0;
				} else {
					
					p = node.parent();
				}
				for(var i:Number=0; i < items.length; i++) {
					
					var insert:XML = <node />;
					insert.@label = items[i];
					insert.@type  = "restaurant";
					tree.dataDescriptor.addChildAt(p, insert, r+i);
				}
				
			}
			/**
			 * Called when the drag operation completes, whether 
			 * successfully or not. The tree is cleared of its
			 * selection.
			 */
			private function onDragComplete( event:DragEvent ) : void
				
			{
				tree.selectedIndex = -1;
			}        
		]]>
	</fx:Script>

	<mx:Panel x="48" y="125" width="447" height="351" layout="absolute" title="Drag onto Tree">    
		<mx:Tree width="186" left="10" top="10" bottom="10" id="tree"
				 labelField="@label"
				 dataProvider="{treeData.node}"
				 dropEnabled="false"
				 dragMoveEnabled="false"
				 dragEnter="onDragEnter(event)"
				 dragOver="onDragOver(event)"
				 dragDrop="onDragDrop(event)">
			
		</mx:Tree>        
		<mx:List width="188" height="206" right="10" bottom="10" id="list"
				 allowMultipleSelection="true"
				 dataProvider="{listData}"
				 dragEnabled="true"
				 dragMoveEnabled="true"
				 dragComplete="onDragComplete(event)">
			
		</mx:List>        
		<mx:Text x="229" y="10" text="Drag from the list below to the tree" width="188" height="39"/>
		
		<mx:Label x="229" y="69" text="restaurants"/>
	</mx:Panel>    
</s:Application>

 

 

 

   Flex4之Tree开发_第7张图片

 

第四:Tree 到Tree及综合拖动示例

 

Xml代码
  1. <spanstyle="font-size: medium;"><?xmlversion="1.0"encoding="utf-8"?> 
  2. <s:Applicationxmlns:fx="http://ns.adobe.com/mxml/2009"  
  3.                xmlns:s="library://ns.adobe.com/flex/spark"  
  4.                xmlns:mx="library://ns.adobe.com/flex/mx"minWidth="955"minHeight="600"xmlns:com="com.*"> 
  5.     <s:layout> 
  6.         <s:BasicLayout/> 
  7.     </s:layout> 
  8.     <fx:Script> 
  9.         <![CDATA[
  10.             import mx.controls.listClasses.ListBase;
  11.             import mx.core.UIComponent;
  12.             import mx.controls.Tree;
  13.             import mx.collections.ArrayCollection;
  14.             import mx.core.DragSource;
  15.             import mx.managers.DragManager;
  16.             import mx.events.DragEvent;
  17.             import mx.events.TreeEvent;
  18.             import flash.events.KeyboardEvent;
  19.             import flash.events.MouseEvent;
  20.             import flash.events.Event;
  21.             import mx.utils.ObjectUtil;
  22.            
  23.            
  24.            
  25.             [Bindable]
  26.             public var selectedNode:Object;
  27.            
  28.             [Bindable]
  29.             public var description:String = "Directions:\n\nTo see the effect of the Spring Loaded Folders select " +
  30.                 "an item in the tree and drag the item over the folders wait, hovering over the folder and " +
  31.                 "it'll open.\n\nIf a folder opens and you did not want it to open move the mouse out of " +
  32.                 "the tree, and it'll restore the original state. \n\nPlay around with the delay to get a " +
  33.                 "desired delay.Hitting spacebar while dragging over a closed folder will open it immediately.";
  34.            
  35.            
  36.             public function treeChanged(event:Event):void {
  37.                 selectedNode=event.currentTarget.selectedItem;
  38.             }
  39.            
  40.             private function onDragOver(event:DragEvent):void{
  41.                 try{
  42.                     if( event.dragInitiator is ListBase ){
  43.                         var list:ListBase = event.dragInitiator as ListBase;
  44.                         if( event.currentTarget != event.dragInitiator){
  45.                             //do what?
  46.                             //trace(mx.utils.ObjectUtil.toString('[currentTarget]'+event.currentTarget));
  47.                         }
  48.                         if(list.indexToItemRenderer(list.calculateDropIndex(event)) != null){
  49.                             var currTree:Tree = Tree(event.currentTarget);
  50.                             var currNodeOver:Object;
  51.                             var rowIndex:int = currTree.calculateDropIndex(event);
  52.                             var hoverTarget:Object = currTree.indexToItemRenderer(rowIndex).data;
  53.                             var parent:Object = currTree.getParentItem(hoverTarget);
  54.                             var tattlerStr:String = new String();
  55.                             var halfRow:int = currTree.rowHeight/2;
  56.                             var certerRowY:int = (rowIndex*currTree.rowHeight)+halfRow;
  57.                             var bottomRowY:int = (rowIndex+1)*currTree.rowHeight;
  58.                            
  59.                             currNodeOver = currTree.indexToItemRenderer(rowIndex).data;
  60.                            
  61.                             DragManager.showFeedback(DragManager.MOVE);
  62.                             currTree.showDropFeedback(event);
  63.                            
  64.                             //trace(ObjectUtil.toString(parent));
  65.                             if( parent != null )
  66.                                 trace('[currTree is a tree]');
  67.                                 //parent.label = 'currTree is a tree';
  68.                                 //parentObject = currTree.getParentItem(hoverTarget);
  69.                             else
  70.                                 trace('[currTree is a tree]');
  71.                             //parent.label = 'currTree is not a tree';
  72.                             //parentObject.label = 'currTree is not a tree';
  73.                            
  74.                             tattlerStr = "Selected Item: " + selectedNode + "\n" + "Over Target: " + hoverTarget.level
  75.                                 + "\n" + "Target Parent: " + 'test'//parent.label
  76.                                 + "\n"
  77.                                 + "calculateDropIndex " + rowIndex
  78.                                 + "\n"
  79.                                 + "halfRow " + halfRow.toString()
  80.                                 + "\n"
  81.                                 + "certerRowY " + certerRowY.toString()
  82.                                 + "\n"
  83.                                 + "bottomRowY " + bottomRowY.toString()
  84.                                 + "\n"
  85.                                 + "mouseY " + currTree.mouseY.toString()
  86.                                 + "\n"
  87.                                 + "isItemOpen " + currTree.isItemOpen(currNodeOver).toString()
  88.                                 + "\n" + "\n";
  89.                            
  90.                             tattler.text = tattlerStr;
  91.                         }else{
  92.                             tattler.text = "No Drop Buddy";
  93.                         }
  94.                     }
  95.                 }catch(err:Error){
  96.                     trace('[error]'+err);
  97.                 }
  98.                
  99.             }
  100.            
  101.             private function onDragDrop(event:DragEvent):void{
  102.                 try{
  103.                     var target:Tree = Tree(event.currentTarget);
  104.                     var list:ListBase = event.dragInitiator as ListBase;
  105.                     var ds:DragSource = event.dragSource;
  106.                     var rowIndex:int = target.calculateDropIndex(event);
  107.                     var hoverTarget:Object = target.indexToItemRenderer(rowIndex).data;
  108.                     var parent:Object = target.getParentItem(hoverTarget);
  109.                     var items:Array = ds.dataForFormat("items") as Array;
  110.                     var i:int;
  111.                    
  112.                     //trace(event.dragInitiator);
  113.                     if( event.dragInitiator is DataGrid ){
  114.                         //do what?
  115.                         //trace(mx.utils.ObjectUtil.toString('[currentTarget]'+event.currentTarget));
  116.                         for (i=0; i < items.length; i++){
  117.                             var tempObj:Object = {};
  118.                             tempObj = items[i];
  119.                             parent.children.addItem(tempObj);
  120.                         }
  121.                        
  122.                         event.preventDefault();
  123.                     }
  124.                 }catch(err:Error){
  125.                     trace('[onDragDropError]'+err);
  126.                 }
  127.                
  128.             }
  129.            
  130.            
  131.             private function onDragEnter(event:DragEvent):void{
  132.                 DragManager.acceptDragDrop(UIComponent(event.currentTarget));
  133.             }
  134.             [Bindable]
  135.             private var treeData:ArrayCollection = new ArrayCollection(
  136.                 [ {label:"Curriculum", level:"Curr", children:new ArrayCollection(
  137.                     [ {label:"cert1", level:"Cert", children:new ArrayCollection(
  138.                         [{label:"c1", level:"Course", type:"prereq"},
  139.                             {label:"c2", level:"Course", type:"prereq"}
  140.                         ])}
  141.                     ])},{label:"Curriculum", level:"Curr", children:new ArrayCollection(
  142.                         [ {label:"cert1", level:"Cert", children:new ArrayCollection(
  143.                             [{label:"c1", level:"Course", type:"prereq"},
  144.                                 {label:"c2", level:"Course", type:"prereq"}
  145.                             ])}
  146.                         ])}
  147.                 ]);
  148.            
  149.             [Bindable]
  150.             private var secondTreeData:ArrayCollection = new ArrayCollection(
  151.                 [ {label:"Curriculum", level:"Curr", children:new ArrayCollection(
  152.                     [ {label:"cert1", level:"Cert", children:new ArrayCollection(
  153.                         [{label:"c1", level:"Course", type:"prereq"},
  154.                             {label:"c2", level:"Course", type:"prereq"}
  155.                         ])}
  156.                     ])},{label:"Curriculum", level:"Curr", children:new ArrayCollection(
  157.                         [ {label:"cert1", level:"Cert", children:new ArrayCollection(
  158.                             [{label:"c1", level:"Course", type:"prereq"},
  159.                                 {label:"c2", level:"Course", type:"prereq"}
  160.                             ])}
  161.                         ])}
  162.                 ]);
  163.            
  164.            
  165.             [Bindable]
  166.             private var gridDP:ArrayCollection = new ArrayCollection(
  167.                 [{label:"c5", level:"Course", type:"prereq"},
  168.                     {label:"c6", level:"Course", type:"prereq"},
  169.                     {label:"c7", level:"Course", type:"prereq"}]);
  170.         ]]> 
  171.     </fx:Script> 
  172.     <fx:Declarations> 
  173.         <!-- 将非可视元素(例如服务、值对象)放在此处 --> 
  174.     </fx:Declarations> 
  175.     <mx:VBoxwidth="100%"height="100%"> 
  176.         <mx:CanvasbackgroundColor="#f3d7ab"borderColor="#000000"borderStyle="outset"width="100%"x="10"height="50%"y="10"horizontalScrollPolicy="off"verticalScrollPolicy="off"> 
  177.              
  178.             <mx:HBoxwidth="100%"height="100%"> 
  179.                 <com:SpringLoadedTreeid="tree1"width="35%"height="100%" 
  180.                                     autoCloseOpenNodes="{autoCloseOpenNodes.selected}"  
  181.                                     autoCloseOnDrop="{autoCloseOnDrop.selected}"  
  182.                                     autoOpenTimerMS="{DelayOpen.value}"  
  183.                                     autoCloseTimerMS="{DelayClose.value}"  
  184.                                     showOpeningIndication="{showOpenIdication.selected}"  
  185.                                     autoCloseOnExit="{autoCloseOnExit.selected}"  
  186.                                     dataProvider="{treeData}" 
  187.                                     mouseDown="treeChanged(event)" 
  188.                                     fontWeight="bold"color="#000000" 
  189.                                     dragEnabled="true"  
  190.                                     dragOver="onDragOver(event)" 
  191.                                     dragMoveEnabled="true" 
  192.                                     dropEnabled="true" 
  193.                                     labelField="label"wordWrap="true" 
  194.                                     fontSize="8"variableRowHeight="true" 
  195.                                     x="41"y="20"/> 
  196.                  
  197.                 <com:SpringLoadedTreeid="tree2"width="35%"height="100%" 
  198.                                     autoCloseOpenNodes="{autoCloseOpenNodes.selected}"  
  199.                                     autoCloseOnDrop="{autoCloseOnDrop.selected}"  
  200.                                     autoOpenTimerMS="{DelayOpen.value}"  
  201.                                     autoCloseTimerMS="{DelayClose.value}"  
  202.                                     showOpeningIndication="{showOpenIdication.selected}"  
  203.                                     autoCloseOnExit="{autoCloseOnExit.selected}"  
  204.                                     dataProvider="{secondTreeData}" 
  205.                                     mouseDown="treeChanged(event)" 
  206.                                     fontWeight="bold"color="#000000" 
  207.                                     dragEnabled="true"  
  208.                                     showRoot="false" 
  209.                                     dragDrop="onDragDrop(event)" 
  210.                                     dragEnter="onDragEnter(event)" 
  211.                                     dragOver="onDragOver(event)" 
  212.                                     dragMoveEnabled="true" 
  213.                                     dropEnabled="true" 
  214.                                     labelField="label"wordWrap="true" 
  215.                                     fontSize="8"variableRowHeight="true" 
  216.                                     x="41"y="20"/> 
  217.                  
  218.                  
  219.                 <mx:DataGriddataProvider="{gridDP}"id="grid1"  
  220.                              dragEnabled="true" 
  221.                              dragMoveEnabled="true"height="100%"> 
  222.                 </mx:DataGrid> 
  223.                  
  224.                 <mx:Texttext="{description}"id="Directions"enabled="true"height="100%"width="30%"/> 
  225.                  
  226.                  
  227.             </mx:HBox> 
  228.         </mx:Canvas> 
  229.         <mx:HBoxwidth="100%"height="50%"> 
  230.             <mx:TextAreax="10"y="368"width="50%"height="100%"id="tattler"/> 
  231.             <mx:Canvaswidth="50%"height="100%"y="446"x="470"> 
  232.                 <mx:CheckBoxid="autoCloseOnDrop"selected="true"label="Return to original state on drop"left="10"right="10"bottom="96"/> 
  233.                 <mx:HSlidervalue="1000"tickInterval="200"snapInterval="200"maximum="2000"allowTrackClick="true"minimum="200"id="DelayOpen"left="255"bottom="174"width="190"/> 
  234.                 <mx:Labeltext="Folder auto open delay ms:{DelayOpen.value}"left="10"bottom="174"textAlign="left"width="248"/> 
  235.                 <mx:CheckBoxid="showOpenIdication"selected="true"label="Show opening indication"left="10"right="10"bottom="122"/> 
  236.                  
  237.                 <mx:HSlidervalue="200"tickInterval="100"snapInterval="100"maximum="1000"allowTrackClick="true"minimum="100"id="DelayClose"bottom="200"width="190"left="255"/> 
  238.                 <mx:Labeltext="Folder auto close delay ms:{DelayClose.value}"left="10"bottom="200"textAlign="left"width="248"/> 
  239.                 <mx:CheckBoxid="autoCloseOpenNodes"selected="true"label="Auto open/close folders on drag over/out"left="10"right="10"bottom="148"/> 
  240.                 <mx:CheckBoxid="autoCloseOnExit"selected="true"label="Auto close folders on tree exit"left="10"right="10"bottom="70"/> 
  241.             </mx:Canvas> 
  242.         </mx:HBox> 
  243.     </mx:VBox> 
  244. </s:Application> 
  245. </span> 

 

<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" 
			   xmlns:s="library://ns.adobe.com/flex/spark" 
			   xmlns:mx="library://ns.adobe.com/flex/mx" minWidth="955" minHeight="600" xmlns:com="com.*">
	<s:layout>
		<s:BasicLayout/>
	</s:layout>
	<fx:Script>
		<![CDATA[
			import mx.controls.listClasses.ListBase;
			import mx.core.UIComponent;
			import mx.controls.Tree;
			import mx.collections.ArrayCollection;
			import mx.core.DragSource;
			import mx.managers.DragManager;
			import mx.events.DragEvent;
			import mx.events.TreeEvent;
			import flash.events.KeyboardEvent;
			import flash.events.MouseEvent;
			import flash.events.Event;
			import mx.utils.ObjectUtil;
			
			
			
			[Bindable]
			public var selectedNode:Object;
			
			[Bindable]
			public var description:String = "Directions:\n\nTo see the effect of the Spring Loaded Folders select " + 
				"an item in the tree and drag the item over the folders wait, hovering over the folder and " + 
				"it'll open.\n\nIf a folder opens and you did not want it to open move the mouse out of " + 
				"the tree, and it'll restore the original state. \n\nPlay around with the delay to get a " + 
				"desired delay.Hitting spacebar while dragging over a closed folder will open it immediately.";
			
			
			public function treeChanged(event:Event):void {
				selectedNode=event.currentTarget.selectedItem;
			}
			
			private function onDragOver(event:DragEvent):void{
				try{
					if( event.dragInitiator is ListBase ){
						var list:ListBase = event.dragInitiator as ListBase;
						if( event.currentTarget != event.dragInitiator){
							//do what?
							//trace(mx.utils.ObjectUtil.toString('[currentTarget]'+event.currentTarget));
						}
						if(list.indexToItemRenderer(list.calculateDropIndex(event)) != null){
							var currTree:Tree = Tree(event.currentTarget);
							var currNodeOver:Object;
							var rowIndex:int = currTree.calculateDropIndex(event);
							var hoverTarget:Object = currTree.indexToItemRenderer(rowIndex).data;
							var parent:Object = currTree.getParentItem(hoverTarget);
							var tattlerStr:String = new String();
							var halfRow:int = currTree.rowHeight/2;
							var certerRowY:int = (rowIndex*currTree.rowHeight)+halfRow;
							var bottomRowY:int = (rowIndex+1)*currTree.rowHeight;
							
							currNodeOver = currTree.indexToItemRenderer(rowIndex).data;
							
							DragManager.showFeedback(DragManager.MOVE);
							currTree.showDropFeedback(event);
							
							//trace(ObjectUtil.toString(parent));
							if( parent != null )
								trace('[currTree is a tree]');
								//parent.label = 'currTree is a tree';
								//parentObject = currTree.getParentItem(hoverTarget);
							else
								trace('[currTree is a tree]');
							//parent.label = 'currTree is not a tree';
							//parentObject.label = 'currTree is not a tree';
							
							tattlerStr = "Selected Item: " + selectedNode + "\n" + "Over Target: " + hoverTarget.level
								+ "\n" + "Target Parent: " + 'test'//parent.label
								+ "\n"
								+ "calculateDropIndex " + rowIndex
								+ "\n" 
								+ "halfRow " + halfRow.toString()
								+ "\n"
								+ "certerRowY " + certerRowY.toString()
								+ "\n"
								+ "bottomRowY " + bottomRowY.toString()
								+ "\n" 
								+ "mouseY " + currTree.mouseY.toString()
								+ "\n"
								+ "isItemOpen " + currTree.isItemOpen(currNodeOver).toString()
								+ "\n" + "\n";
							
							tattler.text = tattlerStr;
						}else{
							tattler.text = "No Drop Buddy";
						}
					}
				}catch(err:Error){
					trace('[error]'+err);
				}
				
			}
			
			private function onDragDrop(event:DragEvent):void{
				try{
					var target:Tree = Tree(event.currentTarget);
					var list:ListBase = event.dragInitiator as ListBase;
					var ds:DragSource = event.dragSource;
					var rowIndex:int = target.calculateDropIndex(event);
					var hoverTarget:Object = target.indexToItemRenderer(rowIndex).data;
					var parent:Object = target.getParentItem(hoverTarget);
					var items:Array = ds.dataForFormat("items") as Array;
					var i:int;
					
					//trace(event.dragInitiator);
					if( event.dragInitiator is DataGrid ){
						//do what?
						//trace(mx.utils.ObjectUtil.toString('[currentTarget]'+event.currentTarget));
						for (i=0; i < items.length; i++){
							var tempObj:Object = {};
							tempObj = items[i];
							parent.children.addItem(tempObj);
						}
						
						event.preventDefault();
					}
				}catch(err:Error){
					trace('[onDragDropError]'+err);
				}
				
			}
			
			
			private function onDragEnter(event:DragEvent):void{
				DragManager.acceptDragDrop(UIComponent(event.currentTarget));
			}
			[Bindable]
			private var treeData:ArrayCollection = new ArrayCollection(
				[ {label:"Curriculum", level:"Curr", children:new ArrayCollection(
					[ {label:"cert1", level:"Cert", children:new ArrayCollection(
						[{label:"c1", level:"Course", type:"prereq"},
							{label:"c2", level:"Course", type:"prereq"} 
						])}
					])},{label:"Curriculum", level:"Curr", children:new ArrayCollection(
						[ {label:"cert1", level:"Cert", children:new ArrayCollection(
							[{label:"c1", level:"Course", type:"prereq"},
								{label:"c2", level:"Course", type:"prereq"} 
							])}
						])}
				]);
			
			[Bindable]
			private var secondTreeData:ArrayCollection = new ArrayCollection(
				[ {label:"Curriculum", level:"Curr", children:new ArrayCollection(
					[ {label:"cert1", level:"Cert", children:new ArrayCollection(
						[{label:"c1", level:"Course", type:"prereq"},
							{label:"c2", level:"Course", type:"prereq"} 
						])}
					])},{label:"Curriculum", level:"Curr", children:new ArrayCollection(
						[ {label:"cert1", level:"Cert", children:new ArrayCollection(
							[{label:"c1", level:"Course", type:"prereq"},
								{label:"c2", level:"Course", type:"prereq"} 
							])}
						])}
				]);
			
			
			[Bindable]
			private var gridDP:ArrayCollection = new ArrayCollection(
				[{label:"c5", level:"Course", type:"prereq"},
					{label:"c6", level:"Course", type:"prereq"},
					{label:"c7", level:"Course", type:"prereq"}]);
		]]>
	</fx:Script>
	<fx:Declarations>
		<!-- 将非可视元素(例如服务、值对象)放在此处 -->
	</fx:Declarations>
	<mx:VBox width="100%" height="100%">
		<mx:Canvas backgroundColor="#f3d7ab" borderColor="#000000" borderStyle="outset" width="100%" x="10" height="50%" y="10" horizontalScrollPolicy="off" verticalScrollPolicy="off">
			
			<mx:HBox width="100%" height="100%" >
				<com:SpringLoadedTree id="tree1" width="35%" height="100%"
									autoCloseOpenNodes="{autoCloseOpenNodes.selected}" 
									autoCloseOnDrop="{autoCloseOnDrop.selected}" 
									autoOpenTimerMS="{DelayOpen.value}" 
									autoCloseTimerMS="{DelayClose.value}" 
									showOpeningIndication="{showOpenIdication.selected}" 
									autoCloseOnExit="{autoCloseOnExit.selected}" 
									dataProvider="{treeData}"
									mouseDown="treeChanged(event)"
									fontWeight="bold" color="#000000"
									dragEnabled="true" 
									dragOver="onDragOver(event)"
									dragMoveEnabled="true"
									dropEnabled="true"
									labelField="label" wordWrap="true"
									fontSize="8" variableRowHeight="true"
									x="41" y="20"/>
				
				<com:SpringLoadedTree id="tree2" width="35%" height="100%"
									autoCloseOpenNodes="{autoCloseOpenNodes.selected}" 
									autoCloseOnDrop="{autoCloseOnDrop.selected}" 
									autoOpenTimerMS="{DelayOpen.value}" 
									autoCloseTimerMS="{DelayClose.value}" 
									showOpeningIndication="{showOpenIdication.selected}" 
									autoCloseOnExit="{autoCloseOnExit.selected}" 
									dataProvider="{secondTreeData}"
									mouseDown="treeChanged(event)"
									fontWeight="bold" color="#000000"
									dragEnabled="true" 
									showRoot="false"
									dragDrop="onDragDrop(event)"
									dragEnter="onDragEnter(event)"
									dragOver="onDragOver(event)"
									dragMoveEnabled="true"
									dropEnabled="true"
									labelField="label" wordWrap="true"
									fontSize="8" variableRowHeight="true"
									x="41" y="20"/>
				
				
				<mx:DataGrid dataProvider="{gridDP}" id="grid1" 
							 dragEnabled="true"
							 dragMoveEnabled="true" height="100%">
				</mx:DataGrid>
				
				<mx:Text text="{description}" id="Directions" enabled="true" height="100%" width="30%"/>
				
				
			</mx:HBox>
		</mx:Canvas>
		<mx:HBox width="100%" height="50%">
			<mx:TextArea x="10" y="368" width="50%" height="100%" id="tattler"/>
			<mx:Canvas width="50%" height="100%" y="446" x="470">
				<mx:CheckBox id="autoCloseOnDrop" selected="true" label="Return to original state on drop" left="10" right="10" bottom="96"/>
				<mx:HSlider value="1000" tickInterval="200" snapInterval="200" maximum="2000" allowTrackClick="true" minimum="200" id="DelayOpen" left="255" bottom="174" width="190"/>
				<mx:Label text="Folder auto open delay ms:{DelayOpen.value}" left="10" bottom="174" textAlign="left" width="248"/>
				<mx:CheckBox id="showOpenIdication" selected="true" label="Show opening indication" left="10" right="10" bottom="122"/>
				
				<mx:HSlider value="200" tickInterval="100" snapInterval="100" maximum="1000" allowTrackClick="true" minimum="100" id="DelayClose" bottom="200" width="190" left="255"/>
				<mx:Label text="Folder auto close delay ms:{DelayClose.value}" left="10" bottom="200" textAlign="left" width="248"/>
				<mx:CheckBox id="autoCloseOpenNodes" selected="true" label="Auto open/close folders on drag over/out" left="10" right="10" bottom="148"/>
				<mx:CheckBox id="autoCloseOnExit" selected="true" label="Auto close folders on tree exit" left="10" right="10" bottom="70"/>
			</mx:Canvas>
		</mx:HBox>
	</mx:VBox>
</s:Application>

 

Flex4之Tree开发_第8张图片

 

你可能感兴趣的:(flex4)