ActionScript - Using the Mouse to Drag Something

Using a mouse to "drag" an item is a recurring problem in user interface design. The basic procedure is

The "Flag" | Using a "flag" Variable | Adding and Removing an Event | Notes | Drag Class | References


The "Flag"

In most programs, I have used a variable as the "flag".

The Flash help suggests another approach - attach and release the Mouse_Move event. I like this because no code is called, and there is no need to test some flag, when the mouse is moving ... until the button is pressed.

The next 2 sections show these techniques. Note that the mouse is moving an object named canvas and that the mouse events are connected to the stage.


Using a "flag" Variable

This ActionScript code works - it leaves the MOUSE_MOVE event attached and checks a "flag" variable.


Adding and Removing an Event

This ActionScript code works - it adds and removes the MOUSE_MOVE event as appropriate.


Notes

A few notes on the above examples


Drag Class

This isn't a lot of code ... but it is required in many programs. As a result, I thought it would be useful to create a class to encapsulate this. If it is done "right", then the class can be expanded to also handle changes in the mouse icon. The following is all the code necessary to use the TMouse class to perform the same function as the two examples above.


References

In the Flash help Provides several examples on how to drag objects. The first example uses the startDrag() method which they admit (and I agree) is fairly limiting. The second example uses the MOUSE_MOVE event and provides much more capability. The third shows how several objects can share the same methods. I strongly suggest reading these.

For related information, scroll to the bottom of the Mouse class help for a custom cursor example - create a graphic that extends Shape, hide the real cursor, draw the graphic, and reposition the image as the mouse moves.

This example suggests disabling the drag and restoring the cursor when the mouse leaves the component (MOUSE_OUT) or the form (MOUSE_LEAVE).


Author: Robert Clemenzi - clemenzi@cpcug.org
URL: http:// cpcug.org / user / clemenzi / technical / Languages / ActionScript / Mouse_Drag.html