Using Listeners

A listener in Java is an object that is used to handle events. In effect, it is implemented to listen for events and then tell the program the required information about that event, which you may then handle. For example, if the player moves the mouse, a listener will alert the program that the mouse has been moved and give details of its position, relative to the component currently occupying that area of the screen. The most commonly used event listeners are shown below and are found in the package java.awt.event.







In this chapter we will concentrate on the KeyListener, MouseListener, and MouseMotionListener interfaces (we will look at the FocusListener toward the end of this chapter also). The following tables show details of the abstract methods defined in these three listeners and the events that invoke them.


void keyPressed(KeyEvent e)

A key is pressed down (these events will continue to occur when the user holds the key down but with a key delay).

void keyReleased(KeyEvent e)

A key is released.

void keyTyped(KeyEvent e)

A key is pressed and then released (note that this event is only posted for keys that are deemed to be type-able, such as alpha characters and numbers and not keys such as F1, Ctrl, and Alt, for example).


void mouseClicked(MouseEvent e)

A mouse button is pressed and then released on a component.

void mouseEntered(MouseEvent e)

Mouse enters a component area.

void mouseExited(MouseEvent e)

Mouse exits a component area.

void mousePressed(MouseEvent e)

A mouse button is pressed on a component.

void mouseReleased(MouseEvent e)

A mouse button is released on a component.


void mouseDragged(MouseEvent e)

A mouse button is held down on a component, and then the mouse is moved.

void mouseMoved(MouseEvent e)

Mouse is moved on a component and no buttons are down.

For convenience, javax.swing.event.MouseInputListener implements all of the methods included in the MouseListener and MouseMotionListener interfaces together.

Information about an event is stored in an event object, which is passed as a parameter to a listener method when it is invoked. This is shown in the previous tables, with the class KeyEvent for events associated with the keyboard and the class MouseEvent for events associated with the mouse.