Java Reference
In-Depth Information
Now we are ready to create a menu and add it to the menu bar:
JMenu fileMenu = new JMenu("File");
menubar.add(fileMenu);
These two lines create a menu labeled
File
and insert it into our menu bar. Finally, we can add menu
items to the menu. The following lines add two items, labeled
Open
and
Quit
, to the
File
menu:
JMenuItem openItem = new JMenuItem("Open");
fileMenu.add(openItem);
JMenuItem quitItem = new JMenuItem("Quit");
fileMenu.add(quitItem);
Exercise 11.5
Add the menu and menu items discussed here to your image-viewer project.
What happens when you select a menu item?
Exercise 11.6
Add another menu called
Help
that contains a menu item named
About
ImageViewer
. (Note: To increase readability and cohesion, it may be a good idea to move the
creation of the menus into a separate method, perhaps named
makeMenuBar
, which is called
from our
makeFrame
method.)
So far, we have achieved half of our task; we can create and display menus. But the second half
is missing—nothing happens yet when a user selects a menu. We now have to add code to react
to menu selections. This is discussed in the next section.
11.4.5 Event handling
Swing uses a very flexible model to deal with GUI input: an
event-handling
model with
event
listeners.
The Swing framework itself and some of its components raise events when something happens
that other objects may be interested in. There are different types of events caused by different
types of actions. When a button is clicked or a menu item is selected, the component raises an
ActionEvent
. When a mouse is clicked or moved, a
MouseEvent
is raised. When a frame is
closed or iconified, a
WindowEvent
is generated. There are many other types of events.
Concept:
Any of our objects can become an event listener for any of these events. When it is a listener,
it will get notified about any of the events it listens to. An object becomes an event listener by
implementing one of several existing listener interfaces. If it implements the right interface, it
can register itself with a component it wants to listen to.
An object can lis-
ten to component
events by imple-
menting an
event-
listener
interface.
Let us look at an example. A menu item (class
JMenuItem
) raises an
ActionEvent
when
it is activated by a user. Objects that want to listen to these events must implement the
ActionListener
interface from the
java.awt.event
package.
There are two alternative styles for implementing event listeners: either a single object listens
for events from many different event sources, or each distinct event source is assigned its own
unique listener. We shall discuss both styles in the next two sections.
Search WWH ::
Custom Search