(Note: This discussion of event listeners pertains to Java versions 1.1 through 1.3; any future versions may or may not use the same event model. Other languages, like C++, may use similar or different event models; I don't know.)
An event listener is a type of
object in a
Java program that is created to handle
events that may or may not occur while the program is being
executed, most commonly
user input (or
interaction, if you prefer) in
graphical programs. (It has occurred to me that an event listener could be useful in
network communication and similar
applications; however, I don't know if Java supports this or not, as I'm only experienced with basic
TCP/IP communication.)
See
Java event model for a general
overview of how Java handles such events.
There are several
types of event listeners, such as
mouse listeners,
key listeners, and
action listeners. As is probaby
obvious, mouse listeners are used for mouse events and key listeners for keypress-related events; action listeners are sort of a general listener, which can be used for when a
button is
clicked on, when 'enter' is pushed in a
text field, and so on.
There are two ways to create a class that can be used as a listener object:
inheritance and
implementation.
Inheritance simply means that you create a
class (often an
inner class) that
inherits from a class like
MouseListener,
KeyListener,
ActionListener, or any other listener-type class. You then override the
instance methods for the events to which you wish the program to
respond. However, not all types of listeners have classes from which you can inherit.
Implementation, the method that seems to be more
common, is when you create a class (again, often an inner class) that, instead of inheriting from a listener class, implements a listener
interface -- which defines several methods which you need to declare in the
body of the class, even if you leave them empty -- that allows an object of that class to be used as a listener of whatever type.
Here's an example of a class that implements
MouseListener, and could be placed on a button (or almost any other
GUI component) to handle several different mouse-related events.
class ButtonMouseListener implements MouseListener {
public void mousePressed(MouseEvent e) {
/*
Code to execute when the mouse button is held down
*/
}
public void mouseEntered(MouseEvent e) {
/*
Code for when the mouse cursor enters the screen area
over the button (or whatever)
*/
}
public void mouseExited(MouseEvent e) {
/*
Code for when the mouse cursor leaves the screen area
over the button
*/
}
public void mouseClicked(MouseEvent e) {
/*
Code for when the button is clicked on by the user
*/
}
public void mouseReleased(MouseEvent e) {
/*
Code for when the mouse button is released after being
pressed and held on the GUI button
*/
}
} // ButtonMouseListener
Well, I think that about wraps it up. Feel free to /msg any questions/comments/corrections!