Using Keyboard Event and dynamic textfield in actionscript 3.0

This is a basic example of keyboard Event and Dynamic textfield.I also want to share you a handful shortcur which i found today using “Flash Builder Burrito”, that is “CTRL + SHIFT + D”, to use just click on top of your function Definition and press this shortcut this will create a multiline comment block for commenting function,  

 package

 {

      import flash.display.MovieClip;

      import flash.events.KeyboardEvent;

      import flash.text.TextField;

      public class KeyBoardEventTest extends MovieClip

      {

           private var outputText:TextField;

           public function KeyBoardEventTest()

           {

                super();

                init()

           }

           /**

            * This function Initilize Event

            */

           protected function init():void

           {

                // creating a dynamic textfield for key logging

                outputText = new TextField();

                outputText.x = 0

                outputText.y = stage.stageHeight >> 1;

                outputText.width = stage.stageWidth;

                outputText.height = stage.stageHeight >> 1;

                outputText.border = true;

                outputText.selectable = true;

                outputText.multiline = true;

                outputText.wordWrap = true;

                addChild(outputText);

                stage.addEventListener(KeyboardEvent.KEY_DOWN,onKeyDown);

                stage.addEventListener(KeyboardEvent.KEY_UP,onKeyUp);

           }

           /**

            * Listener for Keyboard KEY_DOWN Event

            * @param e

            * 

            */          

           protected function onKeyDown(e:KeyboardEvent):void

           {

                trace("onKeyDown # keyCode :"+e.keyCode+", charCode:"+e.charCode);

           }

           /**

            * Listener for Keyboard KEY_UP Event

            * @param e

            * 

            */          

           protected function onKeyUp(e:KeyboardEvent):void

           {

                trace("onKeyUp # keyCode :"+e.keyCode+", charCode:"+e.charCode);

           }

           /**

            * Custom trace function 

            * @param value

            * 

            */          

           private function trace(value:*):void

           {

                outputText.appendText("\n"+String(value));

           }

      }

 }

Setting multiple style names on a Spark Button control in Flex 4 using as3

this post is action script version of http://blog.flexexamples.com/2010/10/27/setting-multiple-style-names-on-a-spark-button-control-in-flex-4  in this post we assigning   multiple style names on a Spark Button control in Flex 4 by setting the styleName property to a space separated list of CSS style names

 <?xml version="1.0" encoding="utf-8"?>

 <s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" 

               xmlns:s="library://ns.adobe.com/flex/spark" 

               xmlns:mx="library://ns.adobe.com/flex/mx"

               minWidth="955" 

               minHeight="600" 

               creationComplete="application1_creationCompleteHandler(event)">

     <fx:Style>

         @namespace s "library://ns.adobe.com/flex/spark";

         @namespace mx "library://ns.adobe.com/flex/mx";

         .boldWeight {

             fontWeight: bold;

         }

         .redColor {

             color: red;

         }

     </fx:Style>

     <fx:Script>

         <![CDATA[

             import mx.events.FlexEvent;

             import spark.components.Button;

             import spark.layouts.HorizontalAlign;

             import spark.layouts.HorizontalLayout;

             import spark.layouts.VerticalAlign;

             import spark.layouts.VerticalLayout;

             protected function application1_creationCompleteHandler(event:FlexEvent):void

             {

                 setLayout();

                 createButtons();

             }

             private function setLayout():void

             {

                 var hl:HorizontalLayout = new HorizontalLayout();

                 hl.verticalAlign = VerticalAlign.MIDDLE;

                 hl.horizontalAlign = HorizontalAlign.CENTER 

                 layout = hl;

             }

             private function createButtons():void

             {

                 var btn1:Button = new Button();

                 btn1.label = "PRE STYLED"

                 btn1.styleName = "redColor boldWeight";

                 addElement(btn1);

                 var btn2:Button = new Button();

                 btn2.label = "CLICK ME TO MAKE ME STYLABLE"

                 btn2.addEventListener(MouseEvent.CLICK,onBtnClick1);

                 addElement(btn2);

             }

             protected function onBtnClick1(e:MouseEvent):void

             {

                 Button(e.target).label = "Click Again to remove style";

                 Button(e.target).styleName = "redColor boldWeight";

                 Button(e.target).removeEventListener(MouseEvent.CLICK,onBtnClick1);

                 Button(e.target).addEventListener(MouseEvent.CLICK,onBtnClick2);

             }

             protected function onBtnClick2(e:MouseEvent):void

             {

                 Button(e.target).label = "CLICK ME TO MAKE ME STYLABLE";

                 Button(e.target).styleName = ""; 

                 Button(e.target).removeEventListener(MouseEvent.CLICK,onBtnClick2);

                 Button(e.target).addEventListener(MouseEvent.CLICK,onBtnClick1);

             }

         ]]>

     </fx:Script>

 </s:Application>

setStyle and clearStyle usages for Spark button control in flex4 using as3

This post is again action script version of http://blog.flexexamples.com/2010/10/27/clearing-a-style-on-the-spark-button-control-in-flex-4/ , this example is showing how to add/remove style from spark component

 <?xml version="1.0" encoding="utf-8"?>

 <s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" 

               xmlns:s="library://ns.adobe.com/flex/spark" 

               xmlns:mx="library://ns.adobe.com/flex/mx" minWidth="955" minHeight="600"

               creationComplete="application1_creationCompleteHandler(event)">

     <fx:Script>

         <![CDATA[

             import flash.text.engine.FontWeight;

             import mx.containers.ControlBar;

             import mx.events.FlexEvent;

             import spark.components.Button;

             import spark.layouts.VerticalLayout;

             private var targetButton:Button;

             protected function application1_creationCompleteHandler(event:FlexEvent):void

             {

                 setLayout();

                 var styleSetter:Button = new Button();

                 styleSetter.label="Set Style";

                 var styleRemover:Button = new Button();

                 styleRemover.label="Remove Style";

                 styleSetter.addEventListener(MouseEvent.CLICK,setButtonStyle);

                 styleRemover.addEventListener(MouseEvent.CLICK,removeButtonStyle);

                 controlBarContent = [styleSetter,styleRemover];

                 targetButton = new Button();

                 addElement(targetButton);

                 targetButton.label = "Targer Button";

             }

             protected function setButtonStyle(e:MouseEvent):void

             {

                 targetButton.setStyle("fontWeight",FontWeight.BOLD);

             }

             protected function removeButtonStyle(e:MouseEvent):void

             {

                 targetButton.clearStyle("fontWeight");    

             }

             private function setLayout():void

             {

                 var vl:VerticalLayout = new VerticalLayout();

                 vl.paddingBottom = 20;

                 vl.paddingLeft = 20;

                 vl.paddingRight = 20;

                 vl.paddingTop = 20;

                 layout = vl;

             }

         ]]>

     </fx:Script>

     <fx:Declarations>

         <!-- Place non-visual elements (e.g., services, value objects) here -->

     </fx:Declarations>

 </s:Application>

unfamiliar typecast issue of array

HI,

Today i am working on a project in which i want to insert an array value to a textfield i use this syntex

tf.text = Array(getValues()).join(“,”);

function getValues():Array
{
//return Array
return new Array(“a”,”s”,”d”,”f”);
}

i got a warning :
Array(x) behaves the same as new Array(x). To cast a value to type Array use the expression x as Array instead of Array(x).

so next time if you want to typecast array use

tf.text = (getValues() as Array).join(“,”);

integer comparision with NaN

Hi,
You may be shocked while comparing a integer variable with NaN like this because default value of a integer is 0

var a:int;

if(a == NaN)
{
// code when a is not initilize
}

This will not provide desired result.


var a:int;
if(isNaN(a))
{
// code when a is not initilize
}

This will also not provide desired result.

Try this code

var a:int;
trace(a);//0
a = 10;
trace(a)//10
a = undefined;
trace(a)//0

Moral of the story: Integer number does not have NaN.

for more info see lukasz comment below

Moving balls

I did change in my previous example and make Balls moveable
  
 
  
 package 
  
 {
  
     import flash.display.Graphics;
  
     import flash.display.MovieClip;
  
     /**
  
      * ...
  
      * @author Jeet Chauhan
  
      */
  
     public class BallWithParameter extends MovieClip
  
     {
  
         
  
         private var color:uint;
  
         private var radius:Number;
  
         
  
         public function BallWithParameter(radius:Number = 10,color:uint=0xffff00) 
  
         {
  
             this.color = color;
  
             this.radius = radius;
  
             draw()
  
         }
  
         
  
         private function draw():void
  
         {
  
             var g:Graphics = graphics;
  
             g.beginFill(color, 1);
  
             g.drawCircle(0, 0, radius);
  
         }
  
         /**
  
          * this will set position of current instance
  
          * @param    dx
  
          * @param    dy
  
          */
  
         public function setPosition(dx:Number, dy:Number):void
  
         {
  
             this.x = dx;
  
             this.y = dy;
  
         }
  
         
  
         /**
  
          * this will move current instance 
  
          * @param    dx
  
          * @param    dy
  
          */
  
         public function moveBy(dx:Number, dy:Number):void
  
         {
  
             this.x += dx;
  
             this.y += dy;
  
         }
  
         
  
     }
  
 
  
 }
  
 
  
 
  
 
  
 package 
  
 {
  
     import flash.display.MovieClip;
  
     import flash.events.Event;
  
     
  
     /**
  
      * ...
  
      * @author Jeet Chauhan
  
      */
  
     public class MultipleBall extends MovieClip
  
     {
  
         private var balls:Array;
  
         public function MultipleBall() 
  
         {
  
             draw()
  
         }
  
         
  
         private function draw():void
  
         {
  
             balls = new Array();
  
             for (var i:int = 0; i &lt; 100; i++) 
  
             {
  
                 var ball:BallWithParameter = new BallWithParameter(Math.random() * 5 + 5, Math.random() * 0xffffff);
  
                 balls.push(ball);
  
                 //ball.setPosition(Math.random() * stage.stageWidth,Math.random() * stage.stageHeight)
  
                 ball.x = Math.random() * stage.stageWidth;
  
                 ball.y = Math.random() * stage.stageHeight;
  
                 addChild(ball);
  
             }
  
             stage.addEventListener(Event.ENTER_FRAME, animate);
  
         }
  
         
  
         private function animate(e:Event):void 
  
         {
  
             for (var i:int = 0; i &lt; 100; i++) 
  
             {
  
                 BallWithParameter(balls[i]).moveBy(Math.random() * 10 - 5, Math.random() * 10 - 5);
  
             }
  
         }
  
         
  
     }
  
 
  
 }  

Second Class


This is improved version of previous post this is more reusable then previous post.
package  
{
	import flash.display.Graphics;
	import flash.display.MovieClip;
	/**
	 * ...
	 * @author Jeet Chauhan
	 */
	public class BallWithParameter extends MovieClip
	{
		private var color:uint;
		private var radius:Number;
		
		public function BallWithParameter(radius:Number = 10,color:uint=0xffff00) 
		{
			this.color = color;
			this.radius = radius;
			draw()
		}
		
		private function draw():void
		{
			var g:Graphics = graphics;
			g.beginFill(color, 1);
			g.drawCircle(0, 0, radius);
		}
		
	}

}

This class initilize random color and radius ball use it as a document class

package  
{
	import flash.display.MovieClip;
	
	/**
	 * ...
	 * @author Jeet Chauhan
	 */
	public class MultipleBall extends MovieClip
	{
		
		public function MultipleBall() 
		{
			draw()
		}
		
		private function draw():void
		{
			var ball:BallWithParameter = new BallWithParameter(Math.random() * 5 + 5, Math.random() * 0xffffff);
			ball.x = Math.random() * stage.stageWidth;
			ball.y = Math.random() * stage.stageHeight;
			addChild(ball);
		}
		
	}

}

this will create multiple circles

package  
{
	import flash.display.MovieClip;
	
	/**
	 * ...
	 * @author Jeet Chauhan
	 */
	public class MultipleBall extends MovieClip
	{
		
		public function MultipleBall() 
		{
			draw()
		}
		
		private function draw():void
		{
			for (var i:int = 0; i < 100; i++) 
			{
				var ball:BallWithParameter = new BallWithParameter(Math.random() * 5 + 5, Math.random() * 0xffffff);
				ball.x = Math.random() * stage.stageWidth;
				ball.y = Math.random() * stage.stageHeight;
				addChild(ball);
			}
			
		}
		
	}

}

Basic AS3 Class Example


This is a simplest example,I hope this will help you to learn as3 and class concept, I love to code and want to share my code with other who want to learn as3 so i am starting a series or tutorials from basic to advanced level

package  
{
	import flash.display.Graphics;
	import flash.display.MovieClip;
	/**
	 * ...
	 * @author Jeet Chauhan
	 */
	public class Ball extends MovieClip
	{
		
		public function Ball() 
		{
			draw()
		}
		
		private function draw():void
		{
			var g:Graphics = graphics;
			g.beginFill(0xff0000, 1);
			g.drawCircle(10, 10, 10);
		}
		
	}

}
In this example we create a class named Ball, which extends MovieClip class, In flash every object which have physical instance must extend MovieClip or Sprite Class,Sprite Class is super class of MovieClip, 

then we get graphics property of MovieClip class

var g:Graphics = graphics;

and then set color to fill

g.beginFill(0xff0000, 1);

then draw a circle on it   

g.drawCircle(10, 10, 10);

create dynamic line using graphics class

This class simply create a line using Graphics class lineTo and moveTo methods hope this will help someone


package 
{
	import flash.display.Graphics;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.MouseEvent;
	
	/**
	 * ...
	 * @author Jeet Chauhan
	 */
	public class drawLine extends Sprite 
	{
		// variable to hold graphics class instanve
		private var g:Graphics;
		
		public function drawLine():void 
		{
			if (stage) init();
			else addEventListener(Event.ADDED_TO_STAGE, init);
		}
		
		private function init(e:Event = null):void 
		{
			removeEventListener(Event.ADDED_TO_STAGE, init);
			// entry point
			g = graphics
			// this will set line thickness from 1 to 4 and a random color
			g.lineStyle(int(Math.random() * 3) + 1, Math.random() * 0xff0000);
			// this will moves the current drawing position to (50,50)
			g.moveTo(50, 50);
			draw();
		}
		
		private function draw():void
		{
			//Draws a line from the current drawing position to (500, 500).
			g.lineTo(500, 500);
		}
		
	}
	
}

as3 increment and decrement operator

What will be the result of snippet in AS3 ,Guess?

var a:int = 1;
a = ++a + a++ + a;
a = a– + –a;
a = ?

Solution

var a:int = 1;
// a == 1
a = ++a + a++ + a;
// ++a is pre increment operator(first increment then assignment) and a++ is post increment operator(first assignment then increment) as3 compiler parse left to right so first ++a then a++ and finally a so result become
// 2 + 2 + 3 = 7

a = a– + –a;
// a– is post decrement operator and –a is pre decrement operator
// 7 + 5 = 12

a = ? // 12

there is a Gotcha ,if you use c concept then you will give wrong answer, because as3 parse From left to right (opposite to c language)
if have any confusion please comment i will try to answer