Java Reference
In-Depth Information
Each type of event has an event class and an event listener interface. They
share a common name, such as ActionEvent and ActionListener, ItemEvent
and ItemListener, and so on. A listener of an event must implement the
corresponding event listener interface. For example, if you want to listen
to an ItemEvent, you write a class that implements the ItemListener
interface.
Now that we've discussed the interfaces, let's look at how to create a listener
and register it with an event source.
Creating an Event Listener
If a listener wants to listen to a particular type of event, then the listener must
implement the corresponding event listener interface. From a programming
point of view, this means you need to write a class that implements the listener
interface. If you want to listen for an ActionEvent, you write a class that imple-
ments ActionListener. If you want to listen for a WindowEvent, you write a
class that implements WindowListener.
I want to show you an example that demonstrates a common design issue of
event handling. I want to write a simple program that contains a Frame with a
Button in it. When the user clicks the Button, I want the color of the Frame to
change to a random color. We have not discussed Button components in detail
yet, but I can tell you that clicking a Button generates an ActionEvent.
Therefore, I need to write a class that implements ActionListener. When the
actionPerformed() method is invoked, I know that the Button has been clicked,
but I want to change the background color of the window. I need to design my
ActionListener class so that it has a reference to the window.
The following RandomColor class is an ActionListener that, in its construc-
tor, initializes a field to point to a Container whose color is to be changed. By
using a reference of type Container, this allows the RandomColor class to
change the color of not just a window, but any Container.
Storing the data and other components that a listener needs as fields in
the listener class is a common technique when designing a listener class.
Typically, these fields are initialized in the constructor or by adding
mutator (set) methods.
import java.awt.*;
import java.awt.event.*;
public class RandomColor implements ActionListener
{
Search WWH ::




Custom Search