You should build the menus before you display them. The typical order is:
MenuBar.Menu.Menu.Menu to the MenuBar.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")
editMenu.add(undo);
editMenu.addSeparator();
MenuItem cut = new MenuItem("Cut")
editMenu.add(cut);
MenuItem copy = new MenuItem("Copy")
editMenu.add(copy);
MenuItem paste = new MenuItem("Paste")
editMenu.add(paste);
MenuItem clear = new MenuItem("Clear")
editMenu.add(clear);
editMenu.addSeparator();
MenuItem selectAll = new MenuItem("Select All");
editMenu.add(selectAll);
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);