Adding menu items and listeners by hand is incredibly tedious. Here is some code
to build up a typical menu.
JMenu m = new JMenu ("Edit");
JMenuItem mi = new JMenuItem("Undo");
mi.addActionListener(this);
m.add(mi);
mi = new JMenuItem("Redo");
mi.addActionListener(this);
m.add(mi);
m.addSeparator();
mi = new JMenuItem("Cut");
mi.addActionListener(this);
m.add(mi);
mi = new JMenuItem("Copy");
mi.addActionListener(this);
m.add(mi);
mi = new JMenuItem("Paste");
mi.addActionListener(this);
m.add (mi );
menuBar. add (m);
Tip
Use a procedure makexenu to take the drudgery out of making menus. This procedure takes three parameters. The first parameter is either a string or a menu. If it is a string, makeMenu makes a menu with that title. The second parameter is an array of items, each of which is a string, a menu item or null. The makeMenu procedure makes a menu item out of each string and a separator out of each null, then adds all items and separators to the menu. The third parameter is the listener for the menu items. (We assume that all menu items have the same listener.) Here is the call to makeMenu that is equivalent to the preceding menu construction code.
mbar.add( makeMenu( "Edit",
new Object[]
{ "Undo",
"Redo",
null,
"Cut",
"Copy",
"Paste",
}, this));
Here's the source code for the makeMenu procedure which can easily be added to
any program that requires a sophisticated menuing system.
private static JMenu makeMenu(Object parent, Object[] items, Object target)
{ JMenu m = null;
if (parent instanceof JMenu)
m = (JMenu)parent;
else if (parent instanceof String)
m = new JMenu((String)parent);
else
return null;
for (int i = 0; i < items.length; i++)
{ if (items[i] instanceof String)
{ JMenuItem mi = new JMenuItem((String)items[i]);
if (target instanceof ActionListener)
mi.addActionListener((ActionListener)target);
m.add(mi);
}
else if (items [i] instanceof JMenuZtem)
{ JMenultem mi = (JMenuItem)items[i];
if(target instanceof ActionListener)
mi.addActionListener((ActionListener)target);
m.add(mi);
}
else if (items[i] == null)
m.addSeparator();
}
return m;
}
Note
In Windows programs, menus are generally defined in an external resource file and tied to the application with resource identifiers. It is possible to build menus programmatically, but it is not commonly done. In Java, there are no external UI resources and menus must be built programmatically.