Flex 4のBorderContainer上でDrag&Dropするサンプル

2011.08.29

この記事は公開されてから1年以上経過しています。情報が古い可能性がありますので、ご注意ください。

Flex 4のBorderContainer上でドラッグ&ドロップするサンプルです。
BorderContainer上のボタンをドラッグ&ドロップで移動できるようにしました。
Flex SDKは4.5.1を使っています。
[SWF]http://public-blog-dev.s3.amazonaws.com/wp-content/uploads/2011/08/SampleDragDrop21.swf,300,200[/SWF]

このサンプルを見るにはFlash Playerがインストールされている必要があります。


以下がサンプルのソースになります。

<?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:Script>
		<![CDATA[
		import mx.core.DragSource;
		import mx.events.DragEvent;
		import mx.events.FlexEvent;
		import mx.managers.DragManager;
		
		private var buttonX:int;
		private var buttonY:int;
			
		private function dragEnterHandler(event:DragEvent):void {
			DragManager.acceptDragDrop(BorderContainer(event.currentTarget));
		}
		
		private function dragDropHandler(event:DragEvent):void {
			var button:Button = Button(event.dragInitiator);
			button.x = event.localX - buttonX;
			button.y = event.localY - buttonY;
		}
			
		private function buttonMouseMoveHandler(event:MouseEvent):void {
			buttonX = event.localX;
			buttonY = event.localY;
			
			var source:DragSource = new DragSource();
			var dragInitiator:Button = Button(event.currentTarget);
			source.addData(dragInitiator, "button");
			DragManager.doDrag(dragInitiator, source, event);	
		}
			
		]]>
	</fx:Script>
	
	<s:BorderContainer width="300" height="200"
			dragEnter="dragEnterHandler(event)"
			dragDrop="dragDropHandler(event)">
		
		<s:Button width="30" height="30"
				x="10" y="10"
				cornerRadius="0"
				mouseMove="buttonMouseMoveHandler(event)"/>
	</s:BorderContainer>
</s:Application>