Java Reference
In-Depth Information
import java.awt.*;public class EventDemo extends Frame
{
private Button go;
public EventDemo(String title)
{
super(title);
go = new Button(“Go”);
//Instantiate a listener object.
RandomColor changer = new RandomColor(this);
//Register the listener with the button.
go.addActionListener(changer);
//Add the button to the frame.
this.setLayout(new FlowLayout());
this.add(go);
}
public static void main(String [] args)
{
Frame f = new EventDemo(“Click the button...”);
f.setSize(300,300);
f.setVisible(true);
}
}
I want to make a few observations about the EventDemo program:
When the RandomColor object is instantiated, a reference to the Frame
is passed in to the constructor. This reference is stored as a field in the
RandomColor object.
■■
The RandomColor object is registered as a listener of the go button.
■■
Each time the go button is clicked, the button generates an ActionEvent
and invokes actionPerformed() on the RandomColor object.
■■
Within actionPerformed(), the RandomColor object generates a random
color and sets it as the background color of the Frame.
■■
The output of the EventDemo program is shown in Figure 13.1. Notice that
the program does not terminate because it is a Frame and we have not handled
the WindowEvent yet. I will show you how to do that next when I discuss the
event adapter classes.
Search WWH ::




Custom Search