When you click a JButton an event is created, known as an action event, which sends a message to another object, known as an action listener. When the listener receives the message, it performs some action. Sending a message or an event to a listener object simply means that some method in the listener object is invoked with the event as the argument. This invocation happens automatically; you will not see the code corresponding to the method invocation. However, you must specify two things:
- For each JButton, you must specify the corresponding listener object. In Java, this is known as registering the listener.
- You must define the methods that will be invoked when the event is sent to the listener. Normally, you will write these methods and you will never write the code for invocation.
Java provides various classes to handle different kinds of events. The action event is handled by the class ActionListener. The class ActionListener contains the method actionPerformed, which includes the code the system is to execute when an action event is generated.
The class ActionListener that handles the action event is a special type of class called an interface. An interface contains only the methods headings; each methods heading is terminated with a semicolon.
Because the method actionPerformed does not contain a body, you cannot instantiate an object of the type ActionListener. One way to register an action listener with an object is to create a class on top of ActionListener so that the required object can be instantiated. The class created must provide the necessary code for the method actionPerformed. The interface ActionListener is contained in the package java.awt.event.
Teaching Tip
|
Tutorials regarding how to write various types of listeners, including ActionListeners, can be found at:
|
No comments:
Post a Comment