Creating Menus

You should build the menus before you display them. The typical order is:

  1. Create a new MenuBar.
  2. Create a new Menu.
  3. Add items to the Menu.
  4. Add the Menu to the MenuBar.
  5. If necessary repeat steps 2 through 4.
  6. Add the MenuBar to the Frame.

The constructors you need are all simple. To create a new MenuBar object:

MenuBar myMenubar = new MenuBar();

To create a new Menu use the Menu(String title) constructor. Pass it the title of the menu you want. For example, to create File and Edit menus,

  Menu fileMenu = new Menu("File");
  Menu editMenu = new Menu("Edit");

MenuItems are created similarly with the MenuItem(String menutext) constructor. Pass it the title of the menu you want like this

MenuItem cut = new MenuItem("Cut");

You can create MenuItems inside the Menus they belong to, just like you created widgets inside their layouts. Menu's have add methods that take an instance of MenuItem. Here's how you'd build an Edit Menu complete with Undo, Cut, Copy, Paste, Clear and Select All MenuItems:

    Menu editMenu = new Menu("Edit");
    MenuItem undo = new MenuItem("Undo") 
    MenuItem cut = new MenuItem("Cut") 
    MenuItem copy = new MenuItem("Copy") 
    MenuItem paste = new MenuItem("Paste") 
    MenuItem clear = new MenuItem("Clear") 
    MenuItem selectAll = new MenuItem("Select All"); 

The addSeparator() method adds a horizontal line across the menu. It's used to separate logically separate functions in one menu.

Once you've created the Menus, you add them to the MenuBar using the MenuBar's add(Menu m) method like this:


Finally when the MenuBar is fully loaded, you add the Menu to a Frame using the frame's setMenuBar(MenuBar mb) method. Given a Frame f this is how you would do it:


Previous | Next | Top | Cafe au Lait

Copyright 1997, 1999, 2002, 2005 Elliotte Rusty Harold
Last Modified April 20, 2005