前面的例子从一个地方移动数据到另一个地方使用了缺省设置,但你也可以很容易地建立 处
理过程来复制那些数据。接下来的例子复制了一个可拖拽的 Box 组件的信息给一个拖拽源
( DragSource )对象,这个对象用来创建一个新的 Box 实例,然后将这个 Box 实例增加到 释
放目标 (drop target) 的显示清单中。
下面有两种形式:1、是增加一新的组件。2、拖动的还是原来的组件。
- <?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" width="100%" height="100%">
- <s:layout>
- <s:HorizontalLayout verticalAlign="middle"/>
- </s:layout>
- <fx:Declarations>
- <!-- 将非可视元素(例如服务、值对象)放在此处 -->
- </fx:Declarations>
- <fx:Script>
- <![CDATA[
- import mx.core.DragSource;
- import mx.core.IUIComponent;
- import mx.events.DragEvent;
- import mx.managers.DragManager;
- private static const FORMAT:String = "box";
- private function mouseDownHandle(evt:MouseEvent):void {
- var initiator:Box = evt.currentTarget as Box;
- var boxData:Object = new Object();
- boxData.width = initiator.width;
- boxData.height = initiator.height;
- boxData.backgroundColor = initiator.getStyle("backgroundColor");
- //DragSource 类中包含正被拖动的数据
- var dragSource:DragSource = new DragSource();
- //addData(data:Object, format:String):void向拖动源添加数据和相应的格式 String。
- dragSource.addData(boxData, FORMAT);
- //启动拖放操作。
- //dragInitiator:IUIComponent — 指定启动拖动的组件的 IUIComponent。
- //dragSource:DragSource — 包含正在拖动的数据的 DragSource 对象。
- //mouseEvent:MouseEvent — 包含与启动拖动相关的鼠标信息的 MouseEvent
- DragManager.doDrag(initiator, dragSource, evt);
- }
- private function dragEnterHandle(evt:DragEvent):void {
- //如果数据源中包含请求的格式,则返回 true;否则,返回 false。
- if(evt.dragSource.hasFormat(FORMAT)) {
- DragManager.acceptDragDrop(Canvas(evt.currentTarget));
- }
- }
- private function dropHandle(evt:DragEvent):void {
- //确定拖动后的位置
- var boxData:Object = evt.dragSource.dataForFormat(FORMAT);
- // var box:Box = new Box();
- // box.width = boxData.width;
- // box.height = boxData.height;
- // box.setStyle("backgroundColor", boxData.backgroundColor);
- //
- // box.x = evt.localX;
- // box.y = evt.localY;
- dragItem.width = boxData.width;
- dragItem.height = boxData.height;
- dragItem.setStyle("backgroundColor", boxData.backgroundColor);
- dragItem.x = evt.localX;
- dragItem.y = evt.localY;
- // canvas.addChild(box);
- }
- ]]>
- </fx:Script>
- <mx:Canvas id="canvas"
- backgroundColor="0xEEEEEE"
- width="80%" height="80%"
- dragEnter="dragEnterHandle(event);"
- dragDrop="dropHandle(event);">
- <mx:Box id="dragItem"
- width="20%" height="20%"
- backgroundColor="0x00FFCC"
- mouseDown="mouseDownHandle(event);" />
- </mx:Canvas>
- </s:Application>