Dragging and Dropping : Drag Drop « Development « Flash / Flex / ActionScript






Dragging and Dropping

 
package{
import flash.display.Sprite;
import flash.events.MouseEvent;
public class Main extends Sprite
{
    private var draggableSprite:Sprite = new Sprite();
    private var droppableSprite:Sprite = new Sprite();
    private var nonDroppableSprite:Sprite = new Sprite();

    public function Main ()
    {
        draggableSprite.graphics.beginFill(0xff0000, 1);
        draggableSprite.graphics.drawCircle(0, 0, 10);
        draggableSprite.graphics.endFill();

        droppableSprite.graphics.beginFill(0x0000ff, 1);
        droppableSprite.graphics.drawRect(0, 0, 100, 100);
        droppableSprite.graphics.endFill();

        nonDroppableSprite.graphics.beginFill(0xff0000, 1);
        nonDroppableSprite.graphics.drawRect(0, 0, 100, 100);
        nonDroppableSprite.graphics.endFill();
        addChild(nonDroppableSprite);
        addChild(droppableSprite);
        addChild(draggableSprite);

        nonDroppableSprite.x = 200;
        droppableSprite.x = 500;
        nonDroppableSprite.y = 100;
        droppableSprite.y = 100;
        draggableSprite.y = 100;

        draggableSprite.addEventListener(MouseEvent.MOUSE_DOWN, 
            startDragSprite);
        draggableSprite.addEventListener(MouseEvent.MOUSE_UP, 
            stopDragSprite);
    }

    private function startDragSprite(mouseEvent:MouseEvent):void
    {
        (mouseEvent.target as Sprite).startDrag();
    }

    private function stopDragSprite(mouseEvent:MouseEvent):void
    {
        var target:Sprite = mouseEvent.target as Sprite;
        if (target.dropTarget == droppableSprite)
        {
            target.stopDrag();
        } else {
            target.x = 0;
        }
    }
}
}

        








Related examples in the same category

1.Dragging and Dropping Objects with the Mouse
2.Drag and drop a Sprite