Java Reference
In-Depth Information
fileMenu.setMnemonic('F'); // Create shortcut
elementMenu.setMnemonic('E'); // Create shortcut
The setMnemonic() method is inherited from the AbstractButton class, so all subclasses of this
class inherit this method. The argument is a character in the String that is the label for the item that is
to be the shortcut character - under Windows the File menu would then pop up if you key Alt+F . The
effect of setMnemonic() is to implement the shortcut and underline the shortcut character letter in
the menu label.
An accelerator is a key combination that you can enter to select an item from a menu. Under Windows, the
Ctrl key is frequently used in combination with a letter as an accelerator for a menu item, so Ctrl+L might be
the combination for the Line item in the Elements menu. For menu items you call the setAccelerator()
method to define an accelerator. For example, for the Line menu item you could write:
lineItem.setAccelerator(KeyStroke.getKeyStroke('L', Event.CTRL _ MASK ));
The KeyStroke class defines a keystroke combination. The static method, getKeyStroke() returns
the KeyStroke object corresponding to the arguments. The first argument is the character and the
second argument specifies the modifier key. The Event class (in java.awt ) defines
Event.SHIFT _ MASK , Event.ALT _ MASK , and what we used here, Event.CTRL _ MASK . If you want to
combine the Alt and Ctrl keys for instance, you can add them - Event.ALT _ MASK +
Event.CTRL _ MASK.
Let's see how this works in practice.
Try It Out - Adding Menu Shortcuts
We can add some shortcuts to Sketcher by amending the statements that add the items to the File menu
in the SketchFrame class constructor:
// Frame for the Sketcher application
import javax.swing.*;
import java.awt.Event;
public class SketchFrame extends JFrame {
// Constructor
public SketchFrame(String title) {
setTitle(title); // Call the base constructor
setDefaultCloseOperation(EXIT _ ON _ CLOSE);
setJMenuBar(menuBar); // Add the menu bar to the window
JMenu fileMenu = new JMenu("File"); // Create File menu
JMenu elementMenu = new JMenu("Elements"); // Create Elements menu
fileMenu.setMnemonic('F'); // Create shortcut
elementMenu.setMnemonic('E'); // Create shortcut
// Construct the file pull down menu as before...
// Add File menu accelerators
newItem.setAccelerator(KeyStroke.getKeyStroke('N',Event.CTRL _ MASK ));
Search WWH ::




Custom Search