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 private method calculate(char opera<strong>to</strong>r) (lines 129–148)<br />

retrieves operands from the text fields in Number 1 and Number 2,<br />

applies the binary opera<strong>to</strong>r on the operands, and sets the result<br />

in the Result text field.<br />

NOTE:<br />

<br />

The menu bar is usually attached <strong>to</strong> the window using the<br />

setJMenuBar method. However, like any other <strong>com</strong>ponent, it<br />

can be placed in a container. For instance, you can place<br />

a menu bar in the south of the container with<br />

BorderLayout.<br />

38.3 Popup Menus<br />

<br />

A popup menu, also known as a context menu, is like a regular<br />

menu, but does not have a menu bar and can float anywhere on the<br />

screen. Creating a popup menu is similar <strong>to</strong> creating a regular<br />

menu. First, you create an instance of JPopupMenu, then you can<br />

add JMenuItem, JCheckBoxMenuItem, JRadioBut<strong>to</strong>nMenuItem, and<br />

separa<strong>to</strong>rs <strong>to</strong> the popup menu. For example, the following code<br />

creates a JPopupMenu and adds JMenuItems in<strong>to</strong> it:<br />

JPopupMenu jPopupMenu = new JPopupMenu();<br />

jPopupMenu.add(new JMenuItem("New"));<br />

jPopupMenu.add(new JMenuItem("Open"));<br />

A regular menu is always attached <strong>to</strong> a menu bar using the<br />

setJMenuBar method, but a popup menu is associated with a parent<br />

<strong>com</strong>ponent and is displayed using the show method in the<br />

JPopupMenu class. You specify the parent <strong>com</strong>ponent and the<br />

location of the popup menu, using the coordinate system of the<br />

parent like this:<br />

jPopupMenu.show(<strong>com</strong>ponent, x, y);<br />

<br />

Cus<strong>to</strong>marily, you display a popup menu by pointing <strong>to</strong> a GUI<br />

<strong>com</strong>ponent and clicking a certain mouse but<strong>to</strong>n, the so-called<br />

popup trigger. Popup triggers are system dependent. In Windows,<br />

the popup menu is displayed when the right mouse but<strong>to</strong>n is<br />

released. In Motif, the popup menu is displayed when the third<br />

mouse but<strong>to</strong>n is pressed and held down.<br />

Listing 38.2 gives an example that creates a text area in a<br />

scroll pane. When the mouse points <strong>to</strong> the text area, clicking a<br />

mouse but<strong>to</strong>n displays a popup menu, as shown in Figure 38.4.<br />

9

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

Saved successfully!

Ooh no, something went wrong!