AWT Events
As Alan noted in lecture, communication between between the user and AWT components, and between one component and onother, achieved using events.
As usual, in Java events are represented objects; these objects are defined by classes of the abstract superclass AWTEvent.
AWTEvents are typically generated by an action, such as a mouse click or a component state change. When this happens, the component originating the event will broadcast the event to all its listeners. It is therefore more flexible than a method call, because events can have multiple recipients, and the originator of an event need not know anything about the recipient.
Under the hood, of course, the event system must use method calls. Therefore, listeners implement a specific interface---for example, MouseListener---so that the event dispatcher can call them. Interested listeners register themselves as clients on the component. Therefore, if you want to know when a button is pressed, you obtain a handle to the button and call the addActionListener() method. Example:
import java.awt.*; import java.awt.event.*; public class ListenerDemo implements ActionListener { public void actionPerformed(ActionEvent e) { System.out.println("foo click!"); } public static void main(String[] args) { // Create frame and add button Frame f = new Frame(); Button myButton = new Button("foo"); f.add(myButton); // Add listener myButton.addActionListener(new ListenerDemo()); f.pack(); f.setVisible(true); } }