This simple button does essentially what I want it to, but it does one annoying thing: Sometimes it stays green (over state) when you mouse out, if you’re moving the cursor very quickly.
Is this a result of bad coding? If not, is there a simple fix? I realize I could put a MOUSE_OVER listener on the stage that would call a public function in the button telling it to go back to UP state, but that’s not very elegant. I also tried adding a ROLL_OUT listener but that didn’t help.
package {
import flash.display.*;
import flash.events.*;
public class TestButton extends Sprite {
private static const UP:String = "up";
private static const OVER:String = "over";
private static const DOWN:String = "down";
private static const OUT:String = "out";
private var btn:Sprite;
private var state:String;
public function TestButton():void {
addEventListener(Event.ADDED_TO_STAGE, init);
}
private function init(e:Event):void {
state = UP;
draw(state);
}
private function draw(state):void {
while (numChildren > 0) removeChildAt(0);
btn = new Sprite();
switch (state) {
case UP:
btn.graphics.beginFill(0xCCCCCC);
break;
case OVER:
btn.graphics.beginFill(0x009900);
break;
case DOWN:
btn.graphics.beginFill(0x0000FF);
}
btn.graphics.drawRect(0, 0, 50, 22);
btn.graphics.endFill();
addChild(btn);
btn.buttonMode = true;
btn.useHandCursor = true;
switch (state) {
case UP:
btn.addEventListener(MouseEvent.MOUSE_OVER, overHandler);
break;
case OVER:
btn.addEventListener(MouseEvent.MOUSE_OUT, outHandler);
btn.addEventListener(MouseEvent.MOUSE_DOWN, downHandler);
break;
case DOWN:
btn.addEventListener(MouseEvent.MOUSE_UP, overHandler);
btn.addEventListener(MouseEvent.MOUSE_OUT, outHandler);
break;
}
}
private function upHandler(e:MouseEvent):void {
state = UP;
draw(state);
}
private function overHandler(e:MouseEvent):void {
state = OVER;
draw(state);
}
private function outHandler(e:MouseEvent):void {
state = UP;
draw(state);
}
private function downHandler(e:MouseEvent):void {
btn.removeEventListener(MouseEvent.MOUSE_OUT, outHandler);
state = DOWN;
draw(state);
}
}
}