Java Reference
In-Depth Information
private Container container;
public RandomColor(Container c)
{
container = c;
}
public void actionPerformed(ActionEvent e)
{
System.out.println(e + “ just occurred.”);
int red, green, blue;
red = (int) (Math.random() * 256);
green = (int) (Math.random() * 256);
blue = (int) (Math.random() * 256);
Color color = new Color(red, green, blue);
container.setBackground(color);
}
}
Registering a Listener with an Event Source
After writing a listener class, you register it with the component from which
you want to handle events. If a component generates an event, the component
has a method of the form add <Event_Name> Listener(). For example, a Button
generates an ActionEvent, and the Button class contains the following method:
public void addActionListener(ActionListener a)
Similarly, a Frame generates a WindowEvent and contains the following
method:
public void addWindowListener(WindowListener w)
Notice that the data types of the parameters of these two methods are inter-
face types. These methods are designed to force the listener class to implement
a specific interface. If you want to listen for the ActionEvent of a Button, you
need to write a class that implements ActionListener so you can pass an
instance to the addActionListener() method. If you want to listen for the
WindowEvent of a Frame, you need to write a class that implements Win-
dowListener so you can pass an instance to the addWindowListener() method.
The following EventDemo class creates a button and registers an instance
of the RandomColor class discussed earlier as a listener of the button. Study
the program and try to determine what the GUI looks like and what the pro-
gram does.
Search WWH ::




Custom Search