Search code examples
actionscript-3flashactionscriptdrag-and-drop

Drag and Drop Text Fields AS3


I'm trying to make text fields drag-able within Flash using Action script 3,

I know how to make regular objects drag-able, but the problem occurs when I try to drag a textfield.

For regular objects I have been using the following code:

Event listeners:

Object.addEventListener(MouseEvent.MOUSE_DOWN, MouseDOWN);
Object.addEventListener(MouseEvent.MOUSE_UP, MouseUP);

Functions:

function MouseDOWN(evt:Event):void {
    evt.target.startDrag();
}

function MouseUP(evt:Event):void {
        evt.target.stopDrag();
}

I've tried many things such as changing 'target' to 'currentTarget' etc, but still can not find a solution.

So my question is, how can I make text fields selectable and drag-able?


Solution

  • startDrag(); and stopDrag(); are methods of the Sprite class, and also inherited by MovieClip, which is a subclass of Sprite

    It's a good idea to check the official Adobe documentation to see what classes inherit what methods;

    Sprite class

    TextField class

    Because Sprite and MovieClip are both base classes of the DisplayObjectContainer class, the simple solution is to simply store the TextField object inside a Sprite object using addChild();

            var textBox:TextField = new TextField;
            textBox.text = "sometext";
            var textContainer:Sprite = new Sprite();
            textContainer.addChild(textBox);
            textContainer.startDrag();
            addChild(textContainer);
    

    You then have all the functionality of Sprite to drag it across the stage.

    Edit:

    Another option would have been to extend the TextField class with your own custom class and implement your own startDrag() and stopDrag() methods.

    You'd then have a public update() method that you could call from your main class that would take in the mouseX, mouseY properties which then sets your object's x, y properties. You could turn this functionality on and off with a simple Boolean.

    It's more work, yes, but if for whatever reason you needed to work with TextField type objects (for example, if you needed to pass it into another object that required it be of type TextField), then your class would also be a type of TextField as it inherits it as a base class.