7.11.2006

SimpleButton Class in Actionscript 3.0

I was playing with the SimpleButton class in AS 3.0 and decided it would be nice to post a simple example with some tips.

The SimpleButton class allows you to create—you guessed it—simple buttons. It's basically a dynamic way to create Buttons with predefined states used in Flash.

Here's the visual (not much to look at):



And the code:

package {

import flash.display.Sprite;
import flash.display.SimpleButton;

public class Source extends Sprite {

public var button:SimpleButton;
private var numButtonWidth:Number = 100;
private var numButtonHeight:Number = 50;

public function Source() {

button = new SimpleButton;
button.upState = drawButtonState(0xDAD8F3);
button.overState = drawButtonState(0x4F42C6);
button.downState = drawButtonState(0xDDF2FF);
button.hitTestState = drawButtonState(0xDDF2FF);
button.useHandCursor = true;
this.addChild(button);

}

private function drawButtonState(rgb:uint):Sprite {
var sprite:Sprite = new Sprite();
sprite.graphics.lineStyle(4,0x33621E,1);
sprite.graphics.beginFill(rgb);
sprite.graphics.drawRoundRect(((this.stage.
stageWidth/2)-(numButtonWidth/2)),((this.
stage.stageHeight/2)-(numButtonHeight/2)),
numButtonWidth,numButtonHeight,10,10);
return sprite;
}

}

}

5 Comments:

At 1/23/09 2:12 PM, Anonymous Anonymous said...

Supposed I wanted to track each dynamic button separately? I've tried using your code, but cannot seem to obtain a unique ID that will house the exact value of i. It always resorts to the last value. I've tried an array, but cannot seem to get it right. Any ideas?

 
At 1/23/09 2:21 PM, Blogger Cahlan said...

You could set a "name" property for each button. Then you can use parent.getChildByName("name") to access that button again.

 
At 1/23/09 6:41 PM, Anonymous Anonymous said...

Right, that works for referring to a specific button. However, I am dynamically generating 7 buttons on the stage in AS3. I want to know which button was clicked in my listener function. So, if the user clicks the third button, some unique value is passed. I tried to assign a string the value "button" + i, but it always returns the last i value (in this case 7). I then tried using an array to store the buttons and their IDs. But I still get the same results. Does this make sense?

 
At 1/23/09 7:33 PM, Blogger Cahlan said...

Right, now I got it. You should be able to catch the even that's passed from your listener to your function. You'll want to access the "target" property of that event. So something like this:

myButton.addEventListener(MouseEvent.CLICK,clickHandler);
function clickHandler(evt:MouseEvent):void {
trace(evt.target);
trace(evt.target.name);
}

 
At 5/14/09 7:20 PM, Anonymous Anonymous said...

hi Cahlan. I've already found the way to get what you wanted. If you still are intersted how to know, ask me sending an email to jim_janer@hotmail.com

 

Post a Comment

Links to this post:

Create a Link

<< Home