We want to use the as language to handle mouse or keyboard events
Then listen and capture to handle mouse and keyboard events
Handling Mouse and keyboard events is similar to the Enterframe event, which has been discussed in section 1.5, just slightly different. For
Mouse events, the main program will not receive directly, you need to listen to it through a visual component (about the visual component of the discussion after the talk).
The following example creates a sprite, adds it to the Visual Component column, and then draws a rectangle over it:
Package {
Import Flash.display.Sprite;
Import flash.events.MouseEvent;
public class Exampleapplication extends Sprite {
private Var _sprite:sprite;
Public Function exampleapplication () {
_sprite = new Sprite ();
AddChild (_sprite);
_sprite.graphics.beginfill (0XFFFFFF);
_sprite.graphics.drawrect (0, 0, 400, 400);
_sprite.graphics.endfill ();
Note: The mouse event name is defined in the MouseEvent class, and event handlers need to be passed into a MouseEvent class
instance, now add a mouse listener to the sprite:
_sprite.addeventlistener (Mouseevent.mouse_down, OnMouseDown);
_sprite.addeventlistener (mouseevent.mouse_up, onMouseUp);
}
Next, define two handler functions onmousedown and onmouseup:
Private Function OnMouseDown (event:mouseevent): void {
_sprite.graphics.linestyle (1, 0, 1);
_sprite.graphics.moveto (MouseX, Mousey);
_sprite.addeventlistener (Mouseevent.mouse_move, OnMouseMove);
}
Private Function OnMouseUp (event:mouseevent): void {
_sprite.removeeventlistener (Mouseevent.mouse_move, OnMouseMove);
}
The OnMouseDown method sets the type of line drawing, moves the brush to the mouse click position, and then adds a third mouse listener
Monitor MouseMove Events
The OnMouseUp method removes the listener with the RemoveEventListener method, which has the same as the AddEventListener method
Grammatical structure, just the opposite.
Finally, define the onmousemove function
Private Function OnMouseMove (event:mouseevent): void {
_sprite.graphics.lineto (MouseX, Mousey);
}
}
}
This creates an event-driven painting program.
Keyboard events are handled simply by listening and responding to keyboard events, and objects that accept these events must be
State. We need to include this line in the main program:
Stage.focus = this;
The following example shows a simple class that listens to the keyboard's KeyDown event, the character code of the output key,
Package {
Import Flash.display.Sprite;
Import flash.events.KeyboardEvent;
public class Exampleapplication extends Sprite {
Public Function exampleapplication () {
Stage.focus = this;
AddEventListener (Keyboardevent.key_down, OnKeyDown);
}
Private Function OnKeyDown (event:keyboardevent): void {
Trace ("Key down:" + event.charcode);
}
}
}
Source: http://flexjs.cn/post/69.html