MouseExample class

Adding an object on the timeline by mouse click

The tutorial consists of 3 classes, the class to add an object by mouse click, a class to add a child button and a class to manipulate the child button separate from its parent. The first class, which we will introduce, is the MouseExample class. When you click with the mouse somewhere in the movie an object will appear on stage. This will be out Document class. Let's start with the script.

We import several classes, in particular important here the MouseEvent and the MovieClip class. The TextField class is only required for demonstartion purposes.

package
{
	import flash.events.MouseEvent;
	import flash.display.MovieClip;
	import flash.text.TextField;
The class extends the MovieClip class, since we have frames. The constructor contains the event listeners for mouse down and up events. The object is the Stage (this.parent).
	public class MouseExample extends MovieClip
	{
	       public function MouseExample()
	       {
	               this.parent.addEventListener(MouseEvent.MOUSE_DOWN, mouseDownHandler);
	               this.parent.addEventListener(MouseEvent.MOUSE_UP, mouseUpHandler);
	       }
When we press the mouse we create an instance of a button of the MyButton class and a TextField with some instructions.
	       private function mouseDownHandler(event:MouseEvent):void
	       {
	               trace("Stage mousedown");
	               var newBut:MyButton = new MyButton (mouseX, mouseY);
	               this.addChild (newBut);
	               var myText:TextField = new TextField();
	               myText.text = "Press the button.";
	               this.addChild(myText);
	       }
When the mouse is up we just do a trace action.
	       private function mouseUpHandler(event:String):void
	       {
	               trace("Stage mouseup");
	       }
	}
}
Next we will give the button, which we placed on stage some function.

previous  |  next