A menu is just Hello World that learned to count. Four labels, one click handler, and a loop so you are not copying and pasting the same rectangle until you quietly resent the entire project. Here is a vertical menu built entirely in code, no library, no timeline, no dragging tiny buttons around a stage with a mouse.
package {
import flash.display.Sprite;
import flash.text.TextField;
import flash.text.TextFormat;
import flash.events.MouseEvent;
public class Menu extends Sprite {
private var items:Array = ["Home", "Work", "About", "Contact"];
public function Menu() {
var format:TextFormat = new TextFormat();
format.size = 18;
for (var i:int = 0; i < items.length; i++) {
var button:Sprite = new Sprite();
button.graphics.beginFill(0x1a1a1a);
button.graphics.drawRect(0, 0, 160, 36);
button.graphics.endFill();
button.y = i * 44;
button.buttonMode = true;
button.mouseChildren = false;
button.name = items[i];
var label:TextField = new TextField();
label.defaultTextFormat = format;
label.textColor = 0xffffff;
label.text = items[i];
label.x = 12;
label.y = 8;
label.selectable = false;
button.addChild(label);
button.addEventListener(MouseEvent.CLICK, onSelect);
addChild(button);
}
}
private function onSelect(event:MouseEvent):void {
trace("You picked: " + event.currentTarget.name);
}
}
}
Reading it top to bottom
The items array is the menu. The whole menu. Change the array and the interface changes with it, which is the entire reason we loop instead of hand placing four buttons like it is 1999. Never hardcode the individual buttons. Your future self will find you, and they will have notes.
Inside the loop each button is a Sprite drawn with the graphics API. beginFill, drawRect, endFill: the three word incantation that means a rectangle exists now. Setting buttonMode to true swaps the cursor to the little pointing hand, which is the difference between clickable and clickable in a way the user actually believes.
The quiet hero here is mouseChildren = false. Leave it out and the click lands on the text field inside the button instead of the button itself, so currentTarget hands you the label and lies about the rest. Switch it off and the button becomes one solid, honest object that reports itself and nothing else.
We stash each label in button.name so the handler knows which one fired. It is cheap, it works, and it is very slightly gross. Part two removes the gross part by loading the whole menu from XML, so the buttons stop being welded to the source code and start being data, which is where menus were always supposed to live.
One last note. trace() prints to the output panel and is the AS3 equivalent of console.log, which means it is the only friend you have at two in the morning. Treat it well.