Events and Their Associated Listeners

  Return to the Java Programming Corner.


Whenever a user types a character at the keyboard or pushes the mouse button, an event occurs. When this happens, any object can be notified of this event. All the object has to do is implement the appropriate interface (some of those interfaces are listed below) and be registered as an event listener on the appropriate event source. Swing components are capable of generating many kinds of events. The table listed in the next section attempts to list a few of them and their associated listener type.

When working with event listeners, keep in mind that each event is represented by an object that provides information about the event and identifies the event source.

Most event sources will be a component, but other kinds of object can also be event sources.

Each event source can have multiple listeners registered to it. Conversely a single listener can register with multiple event sources.

Example of Events and Their Associated Event Listeners

Act that Results in the Event Listener Type
User clicks a button.
User presses <RETURN> while typing in a text field.
User chooses a menu item.
User closes a frame (the main window). WindowListener
User presses a mouse button while the cursor is over a component. MouseListener
User moves the mouse over a component. MouseMotionListener
Component becomes visible. ComponentListener
Component gets the keyboard focus FocusListener
Table or list selection changes ListSelectionListener