Java Reference
In-Depth Information
KeyEvent.VK
-
Q, ActionEvent.CTRL
-
MASK));
menu.add (menuExit);
menuExit.addActionListener (f);
// Add the menu bar to the frame.
f.setJMenuBar (mb);
f.getContentPane ().add (drawingPanel);
f.setSize (new Dimension (240,180));
f.setVisible (true);
}
// main
/** Respond to the menu items. **/
public void actionPerformed (ActionEvent e){
String cmd = e.getActionCommand ();
// Exit program
if (cmd.equals ("Exit"))
System.exit (0);
else if (cmd.equals ("Open"))
// Put code here to open a file
System.out.println ("Open");
}// actionPerformed
}// class FrameMenuApp
...DrawingPanel
class same as for
FrameApp
example . . .
This program goes as the previous one except that it creates a menu bar with a
single menu labeled “File”. The File menu holds two items - Open and Exit -
and a separator.
The menu bar has a simple no argument constructor and is added to the frame
with the
setMenuBar()
method. The
JMenu
constructor passes the title as a
parameter. A mnemonic allows for the selection of a menu or menu item via the
keyboard. The following line assigns the
Alt-f
key pair to bring the focus on
the File menu:
menu.setMnemonic (KeyEvent.VK
-
F);
The “F” in the File label will be underlined to indicate that it is the mnemonic
key. A constructor for
JMenuItem
provides for setting the mnemonic with the
second parameter, as in
JMenuItem menuOpen = new JMenuItem ("Open", KeyEvent.VK
-
O);
This line defines the “Open” item in the File drop-down menu with the mnemonic
key pair set to
Alt-O
.
Search WWH ::
Custom Search