Creating an application with the MenuBar component

In this example, you drag a MenuBar component to the Stage, add code to add menu items to it, and attach a listener to the menu to respond to the selection of a menu item.

To use a MenuBar component in an application:

  1. Select File > New and choose Flash File (ActionScript 2.0).
  2. Drag the MenuBar component from the Components panel to the Stage.
  3. Position the menu at the top of the Stage for a standard layout.
  4. Select the MenuBar instance and, in the Property inspector, enter the instance name my_mb.
  5. In the Actions panel on Frame 1, enter the following code:
    import mx.controls.Menu;
    import mx.controls.MenuBar;
    
    var my_mb:MenuBar;
    
    var my_menu:Menu = my_mb.addMenu("File");
    my_menu.addMenuItem({label:"New", instanceName:"newInstance"});
    my_menu.addMenuItem({label:"Open", instanceName:"openInstance"});
    my_menu.addMenuItem({label:"Close", instanceName:"closeInstance"});
    

    This code adds a File menu to the MenuBar instance. It then uses a Menu method to add three menu items: New, Open, and Close.

  6. In the Actions panel on Frame 1, enter the following code:
    //Create listener object.
    var mbListener:Object = new Object();
    mbListener.change = function(evt_obj:Object) {
     var menuItem_obj:Object = evt_obj.menuItem;
     switch (menuItem_obj.attributes.instanceName) {
     case "newInstance":
      trace("New menu item");
      break;
     case "openInstance":
      trace("Open menu item");
      break;
     case "closeInstance":
      trace("Close menu item");
      break;
     }
     trace(menuItem_obj);
    };
    
    //Add listener.
    my_menu.addEventListener("change", mbListener);
    

    This code creates a listener object, mblistener, that catches a menu item selection and displays its name and the value of the menu item object.

    NOTE

    You must call the addEventListener() method to register the listener with the menu instance, not with the menu bar instance.

  7. Select Control > Test Movie to test the MenuBar component.