MenuBar
.
Menu
.
Menu
.
MenuBar
to the Frame
.
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");
MenuItem
s 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 MenuItem
s inside the Menu
s 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 Menu
s, 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);