您的位置:寻梦网首页编程乐园Java天地Core JavaJava Lecture Notes

previous.gif
 (3087 bytes)

next.gif
 (2959 bytes)


Content Index

Content Page # 16

AWT events and listeners

AWT components interact by sending events to one another. Events are handled by listeners. For your program to interact with the user, it must define listeners for its GUI components.

So far we have seen how to create a user interface which could be quite complex. However, as yet the user interface has no means of interacting with the rest of the program.

Consider a simple program: an applet that has one button. When the button is clicked it does something (it doesn't matter what, at this stage). For the button to do anything at all, we must define a listener for it. The listener is the object that will be notified when the user clicks the button.

The type of listener to create will depend on the type of object. For buttons we require an action listener (the full Java documentation describes the listeners that are appropriate for each object). The method that defines a listener for the button is addActionLister(). So to create a button, put it in the applet's display, and define a listener we would write:

Button myButton = new Button ("Click me!");

add(myButton);

myButton.addActionListener(...);

where the dots (&) indicate something missing. What are we going to put in place of the dots? It can be any object that is a subclass of ActionListener. Note that ActionListener is an interface, not a class. We can make any object a subclass of ActionListener, provided that it provides an implementation for the methods that ActionListener specifies. If you refer to the on-line documentation, you will find that it only specifies one method:

public void actionPerformed (ActionEvent e);

In simple cases, we may define the applet itself to be the action listener for the buttons it contains. This method is not very flexible, but works well for simple applets. So the outline of the applet so far is:

import java.awt.*

import java.awt.event.*;

import java.applet.Applet;

class MyApplet extends Applet implements ActionListener

{

public MyApplet()

{

  super();

Button myButton = new Button ("Click me!");

add(myButton);

myButton.addActionListener(this);

}

public void actionPerformed (ActionEvent e)

{

  // Do something here when the user clicks the button

}

} // class

The line

myButton.addActionListener(this);

means make 'this' (i.e., this applet) the listener for the button called 'myButton'. Whenever the button is clicked, Java will call the method actionPerformed. The ActionEvent object which is passed into the method can be used to distinguish which button was clicked if the same listener is listening to a number of different buttons.

A more sophisticated method for handling events is to use different classes to act as listeners for each type of object in use. It is also possible to make objects 'listen' to themselves.

Back to top

basicline.gif (170 bytes)