ptg7068951
202 HOUR 15:Responding to User Input
Second, the class must use the implementskeyword to declare that it sup-
ports one or more listening interfaces. The following statement creates a
class that uses ActionListener, an interface for responding to button and
menu clicks:
public classGraph implementsActionListener {
EventListenerinterfaces enable a component of a GUI to generate user
events. Without one of the listeners in place, a component cannot do any-
thing that can be heard by other parts of a program. Aprogram must
include a listener interface for each type of component to which it listens.
To have the program respond to a mouse-click on a button or the Enter key
being pressed in a text field, you must include the ActionListenerinter-
face. To respond to the use of a choice list or check boxes, you need the
ItemListenerinterface.
When you require more than one interface in the same class, separate their
names with commas after the implementskeyword, as in this code:
public classGraph3D implementsActionListener, MouseListener {
// ...
}
Setting Up Components to Be Heard
After youhave implemented the interface needed for a particular compo-
nent, you must set that component to generate user events. The
ActionListenerinterface listens for action events, such as a button-click or
the press of the Enter key. To make a JButtonobject generate an event,
employ the addActionListener()method, as in the following:
JButton fireTorpedos = new JButton(“Fire torpedos”);
fireTorpedos.addActionListener(this);
This code creates the fireTorpedosbutton and calls the button’s
addActionListener()method. The thiskeyword used as an argument to
the addActionListener()method indicates the current object receives the
user event and handles it as needed.
Handling User Events
When a user event is generated by a component that has a listener, a
method is called automatically. The method must be found in the class
specified when the listener was attached to the component.
NOTE
Thethiskeyword confuses a
lot of readers when they are
first introduced to it. this
refers to the object in which the
keyword appears. So,if you cre-
ate a LottoMadnessclass and
usethisin a statement inside
that class,it refers to the
LottoMadnessobject executing
the code.