Java Reference
In-Depth Information
Note that the
ArrayList
of characters can be defined as
final
because the location
of the
ArrayList
does not change. The only data that could change is the content of the
ArrayList
.
10.3 Event Listeners
One can associate an event listener with an event source. When an event occurs, a
method of the event listener is called and the event object is passed as a parameter. Examples
of events include window movement, keystroke, mouse movement, button being pressed,
and so on. Examples of event sources include windows, panels, buttons, menus, and other
graphical user interface components. The event listener is an object that is created by the
programmer to listen for an event. The event listener should inherit the interface that is
responsible for the particular type of event.
10.3.1 Key Listeners
In order to complete our typing game, we need to be able to capture keystrokes. Note
that the
Scanner
class does not suce. For example, consider the following code.
Scanner keyboard =
new
Scanner(System. in) ;
String s = keyboard . next () ;
This will require the user to enter a character and then press
Enter
.The
Scanner
class
only processes user input after the
Enter
key is pressed on the keyboard. In order to capture
keystrokes, we need to create a listener that listens for key strokes.
When creating event handling code, one needs to always identify the
event source
,
the
event
,andthe
event listener
, where all three will be objects. The event listener
and the event source are objects that need to be created by the programmer. The
event object is automatically created by Java. After creating the event source and the
event listener, one needs to
register
the event listener with the event source. When the
event occurs, the event source calls a method of the event listener and sends the event
object as a parameter.
In our example, we can create a window (i.e.,
JFrame
) to be the event source. Note
that only graphical components can capture keystrokes and a window is the simplest ex-
ample. Next, we need to create a keystroke listener. Our listener will inherit from the
interface
KeyListener
. Here is what the interface looks like, where the interface is defined
in
java.awt.*
.
{
void
keyPressed (KeyEvent e ) ;
void
keyReleased (KeyEvent e ) ;
void
keyTyped(KeyEvent e ) ;
interface
KeyListener
}
In order to listen for keystrokes, one needs to perform the following tasks.
1. Create a class that overrides the three methods of the
KeyListener
interface.