MenuDemopublic class MenuDemo extends Frame implements ActionListener, ItemListenerDemonstrate Menus and the MenuBar class/MenuContainer interface
This version uses 1.1 action handling and MenuShortcut. The action
handling is incomplete; realistically, each MenuItem would have its
own, task-specific ActionListener; this would handle the MenuShortcuts
and the CheckboxMenuItems correctly. |
Fields Summary |
---|
MenuBar | mb | Menu | fmFile, Options, Help | Menu | om | Menu | hm | Menu | opSubmOptions Sub-Menu | MenuItem | exitItemThe MenuItem for exiting. | CheckboxMenuItem | cbAn option that can be on or off. |
Constructors Summary |
---|
MenuDemo(String s)
super("MenuDemo: " + s);
Container cp = this;
cp.setLayout(new FlowLayout());
mb = new MenuBar();
setMenuBar(mb); // Frame implements MenuContainer
MenuItem mi;
// The File Menu...
fm = new Menu("File");
fm.add(mi = new MenuItem("Open", new MenuShortcut('O")));
mi.addActionListener(this);
fm.add(mi = new MenuItem("Close", new MenuShortcut('W")));
mi.addActionListener(this);
fm.addSeparator();
fm.add(mi = new MenuItem("Print", new MenuShortcut('P")));
mi.addActionListener(this);
fm.addSeparator();
fm.add(mi = new MenuItem("Exit", new MenuShortcut('Q")));
exitItem = mi; // save for action handler
mi.addActionListener(this);
mb.add(fm);
// The Options Menu...
om = new Menu("Options");
cb = new CheckboxMenuItem("AutoSave");
cb.setState(true);
cb.addItemListener(this);
om.add(cb);
opSubm = new Menu("SubOptions");
opSubm.add(new MenuItem("Alpha"));
opSubm.add(new MenuItem("Gamma"));
opSubm.add(new MenuItem("Delta"));
om.add(opSubm);
mb.add(om);
// The Help Menu...
hm = new Menu("Help");
hm.add(mi = new MenuItem("About"));
mi.addActionListener(this);
hm.add(mi = new MenuItem("Topics"));
mi.addActionListener(this);
mb.add(hm);
mb.setHelpMenu(hm); // needed for portability (Motif, etc.).
// the main window
cp.add(new MyLabel("Menu Demo Window", 200, 150));
pack();
|
Methods Summary |
---|
public void | actionPerformed(java.awt.event.ActionEvent evt)Handle action events.
// System.out.println("Event " + evt);
String cmd;
if ((cmd = evt.getActionCommand()) == null)
System.out.println("You chose a menu shortcut");
else
System.out.println("You chose " + cmd);
Object cmp = evt.getSource();
// System.out.println("Source " + cmp);
if (cmp == exitItem)
System.exit(0);
| public void | itemStateChanged(java.awt.event.ItemEvent e)The CheckBoxMenuItems send a different message
System.out.println("AutoSave is set " + cb.getState());
| public static void | main(java.lang.String[] arg)
new MenuDemo("Testing 1 2 3...").setVisible(true);
|
|