Capturing mouse input

Mouse clicks create mouse events that can be used to trigger interactive functionality. You can add an event listener to the Stage to listen for mouse events that occur anywhere within the SWF file. You can also add event listeners to objects on the Stage that inherit from InteractiveObject (for example, Sprite or MovieClip); these listeners are triggered when the object is clicked.

As with keyboard events, mouse events bubble. In the following example, because square is a child of the Stage, the event dispatches both from the sprite square as well as from the Stage object when the square is clicked:

var square:Sprite = new Sprite();
square.graphics.beginFill(0xFF0000);
square.graphics.drawRect(0,0,100,100);
square.graphics.endFill();
square.addEventListener(MouseEvent.CLICK, reportClick);
square.x =
square.y = 50;
addChild(square);

stage.addEventListener(MouseEvent.CLICK, reportClick);

function reportClick(event:MouseEvent):void
{
    trace(event.currentTarget.toString() + 
" dispatches MouseEvent. Local coords [" +
event.localX + "," + event.localY + "] Stage coords [" +
event.stageX + "," + event.stageY + "]"); }

In the previous example, notice that the mouse event contains positional information about the click. The localX and localY properties contain the location of the click on the lowest child in the display chain. For example, clicking at the top-left corner of square reports local coordinates of [0,0] because that is the registration point of square. Alternatively, the stageX and stageY properties refer to the global coordinates of the click on the Stage. The same click reports [50,50] for these coordinates, because square was moved to these coordinates. Both of these coordinate pairs can be useful depending on how you want to respond to user interaction.

The MouseEvent object also contains altKey, ctrlKey, and shiftKey Boolean properties. You can use these properties to check if the Alt, Ctrl, or Shift key is also being pressed at the time of the mouse click.

Creating drag-and-drop functionality

Drag-and-drop functionality allows users to select an object while pressing the left mouse button, move the object to a new location on the screen, and then drop it at the new location by releasing the left mouse button. The following code shows an example of this:

import flash.display.Sprite;
import flash.events.MouseEvent;

var circle:Sprite = new Sprite();
circle.graphics.beginFill(0xFFCC00);
circle.graphics.drawCircle(0, 0, 40);

var target1:Sprite = new Sprite();
target1.graphics.beginFill(0xCCFF00);
target1.graphics.drawRect(0, 0, 100, 100);
target1.name = "target1";

var target2:Sprite = new Sprite();
target2.graphics.beginFill(0xCCFF00);
target2.graphics.drawRect(0, 200, 100, 100);
target2.name = "target2";

addChild(target1);
addChild(target2);
addChild(circle);

circle.addEventListener(MouseEvent.MOUSE_DOWN, mouseDown) 

function mouseDown(event:MouseEvent):void
{
    circle.startDrag();
}
circle.addEventListener(MouseEvent.MOUSE_UP, mouseReleased);

function mouseReleased(event:MouseEvent):void
{
    circle.stopDrag();
    trace(circle.dropTarget.name);
}

For more details, see Creating drag-and-drop interaction.

Customizing the mouse cursor

The mouse cursor (mouse pointer) can be hidden or swapped for any display object on the Stage. To hide the mouse cursor, call the Mouse.hide() method. Customize the cursor by calling Mouse.hide(), listening to the Stage for the MouseEvent.MOUSE_MOVE event, and setting the coordinates of a display object (your custom cursor) to the stageX and stageY properties of the event. The following example illustrates a basic execution of this task:

var cursor:Sprite = new Sprite();
cursor.graphics.beginFill(0x000000);
cursor.graphics.drawCircle(0,0,20);
cursor.graphics.endFill();
addChild(cursor);

stage.addEventListener(MouseEvent.MOUSE_MOVE,redrawCursor);
Mouse.hide();

function redrawCursor(event:MouseEvent):void
{
    cursor.x = event.stageX;
    cursor.y = event.stageY;
}

Customizing the context menu

Every object that inherits from the InteractiveObject class can have a unique context menu, which is displayed when a user right-clicks within the SWF file. Several commands are included by default, including Forward, Back, Print, Quality, and Zoom.

You can remove all the default commands from the menu, except for the Settings and About commands. Setting the Stage property showDefaultContextMenu to false removes these commands from the context menu.

To create a customized context menu for a specific display object, create a new instance of the ContextMenu class, call the hideBuiltInItems() method, and assign that instance to the contextMenu property of that DisplayObject instance. The following example provides a dynamically drawn square with a context menu command to change it to a random color:

var square:Sprite = new Sprite();
square.graphics.beginFill(0x000000);
square.graphics.drawRect(0,0,100,100);
square.graphics.endFill();
square.x =
square.y = 10;
addChild(square);

var menuItem:ContextMenuItem = new ContextMenuItem("Change Color");
menuItem.addEventListener(ContextMenuEvent.MENU_ITEM_SELECT,changeColor);
var customContextMenu:ContextMenu = new ContextMenu();
customContextMenu.hideBuiltInItems();
customContextMenu.customItems.push(menuItem);
square.contextMenu = customContextMenu;

function changeColor(event:ContextMenuEvent):void
{
    square.transform.colorTransform = getRandomColor();
}
function getRandomColor():ColorTransform
{
    return new ColorTransform(Math.random(), Math.random(), 
Math.random(),1,(Math.random() * 512) - 255,
(Math.random() * 512) -255, (Math.random() * 512) - 255, 0); }

Managing focus

An interactive object can receive focus, either programmatically or through a user action. In both cases, setting the focus changes the object's focus property to true. Additionally, if the tabEnabled property is set to true, the user can pass focus from one object to another by pressing the Tab key. Note that the tabEnabled value is false by default, except in the following cases:

In each of these situations, you can add a listener for FocusEvent.FOCUS_IN or FocusEvent.FOCUS_OUT to provide additional behavior when focus changes. This is particularly useful for text fields and forms, but can also be used on sprites, movie clips, or any object that inherits from the InteractiveObject class. The following example shows how to enable focus cycling with the Tab key and how to respond to the subsequent focus event. In this case, each square changes color as it receives focus. <updated code Oct. 11, 2007>

NOTE

 

The Flash authoring tool uses keyboard shortcuts to manage focus; therefore, to properly simulate focus management, SWF files should be tested in a browser rather than within Flash.

var rows:uint = 10;
var cols:uint = 10;
var rowSpacing:uint = 25;
var colSpacing:uint = 25;
var i:uint;
var j:uint;
for (i = 0; i < rows; i++)
{
    for (j = 0; j < cols; j++)
    {
        createSquare(j * colSpacing, i * rowSpacing, (i * cols) + j);
    }
}

function createSquare(startX:Number, startY:Number, tabNumber:uint):void
{
    var square:Sprite = new Sprite();
    square.graphics.beginFill(0x000000);
    square.graphics.drawRect(0, 0, colSpacing, rowSpacing);
    square.graphics.endFill();
    square.x = startX;
    square.y = startY;
    square.tabEnabled = true;
    square.tabIndex = tabNumber;
    square.addEventListener(FocusEvent.FOCUS_IN, changeColor);
    addChild(square);
}
function changeColor(event:FocusEvent):void
{
    event.target.transform.colorTransform = getRandomColor();
}
function getRandomColor():ColorTransform
{
    // Generate random values for the red, green, and blue color channels.
    var red:Number = (Math.random() * 512) - 255;
    var green:Number = (Math.random() * 512) - 255;
    var blue:Number = (Math.random() * 512) - 255;
    
    // Create and return a ColorTransform object with the random colors.
    return new ColorTransform(1, 1, 1, 1, red, green, blue, 0);
}

Flash CS3

Take a survey


 

Send me an e-mail when comments are added to this page | Comment Report

Current page: http://livedocs.adobe.com/flash/9.0/main/00000312.html