19.09.2015 Views

Prentice.Hall.Introduction.to.Java.Programming,.Brief.Version.9th.(2014).[sharethefiles.com]

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

The new icons and mnemonics are shown in Figure 38.2(c). You can<br />

also use JMenuItem construc<strong>to</strong>rs like the ones that follow <strong>to</strong><br />

construct and set an icon or mnemonic in one statement.<br />

public JMenuItem(String label, Icon icon);<br />

public JMenuItem(String label, int mnemonic);<br />

By default, the text is at the right of the icon. Use<br />

setHorizontalTextPosition(SwingConstants.LEFT) <strong>to</strong> set the text <strong>to</strong><br />

the left of the icon.<br />

<br />

To select a menu, press the ALT key and the mnemonic key. For<br />

example, press ALT+F <strong>to</strong> select the File menu, and then press<br />

ALT+O <strong>to</strong> select the Open menu item. Keyboard mnemonics are<br />

useful, but they only let you select menu items from the<br />

currently open menu. Key accelera<strong>to</strong>rs, however, let you select a<br />

menu item directly by pressing the CTRL and accelera<strong>to</strong>r keys. For<br />

example, by using the following code, you can attach the<br />

accelera<strong>to</strong>r key CTRL+O <strong>to</strong> the Open menu item:<br />

jmiOpen.setAccelera<strong>to</strong>r(KeyStroke.getKeyStroke<br />

(KeyEvent.VK_O, ActionEvent.CTRL_MASK));<br />

The setAccelera<strong>to</strong>r method takes a KeyStroke object. The static<br />

method getKeyStroke in the KeyStroke class creates an instance of<br />

the keystroke. VK_O is a constant representing the O key, and<br />

CTRL_MASK is a constant indicating that the CTRL key is<br />

associated with the keystroke.<br />

NOTE: As shown in Figure 17.1, AbstractBut<strong>to</strong>n is the<br />

superclass for JBut<strong>to</strong>n and JMenuItem, and JMenuItem is a<br />

superclass for JCheckBoxMenuItem, JMenu, and<br />

JRadioBut<strong>to</strong>nMenuItem. The menu <strong>com</strong>ponents are very<br />

similar <strong>to</strong> but<strong>to</strong>ns.<br />

38.2.3 Example: Using Menus<br />

This section gives an example that creates a user interface <strong>to</strong><br />

perform arithmetic. The interface contains labels and text fields<br />

for Number 1, Number 2, and Result. The Result text field<br />

displays the result of the arithmetic operation between Number 1<br />

and Number 2. Figure 38.3 contains a sample run of the program.<br />

Figure 38.3<br />

Arithmetic operations can be performed by clicking but<strong>to</strong>ns or by<br />

choosing menu items from the Operation menu.<br />

Here are the major steps in the program (Listing 38.1):<br />

5

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!