Creating Menus

It's easiest to 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. If necessary repeat steps 2 and 3.
  5. 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");
    editMenu.add(new MenuItem("Undo"));
    editMenu.addSeparator();
    editMenu.add(new MenuItem("Cut"));
    editMenu.add(new MenuItem("Copy"));
    editMenu.add(new MenuItem("Paste"));
    editMenu.add(new MenuItem("Clear"));
    editMenu.addSeparator();
    editMenu.add(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:

    myMenubar.add(fileMenu);
    myMenubar.add(editMenu);
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:

    f.setMenuBar(myMenuBar);

Previous | Next | Top
Last Modified July 1, 1999
Copyright 1997, 1999 Elliotte Rusty Harold
elharo@metalab.unc.edu