Java Reference
In-Depth Information
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
, which contains only the method
actionPerformed
. In the method
actionPerformed
, you include the code that you
want the system 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
. In Java,
interface
is a reserved word. Roughly speaking, an
interface
is a class
that contains only the method headings, and each method
heading is
terminated with a
semicolon. For example,
the definition of
the
interface
ActionListener
containing the method
actionPerformed
is:
6
public interface
ActionListener
{
public void
actionPerformed(ActionEvent e);
}
Because the method
actionPerformed
does not contain a body, Java does not allow
you to instantiate an object of type
ActionListener
. So how do you register an action
listener with the object
calculateB
?
One way is as follows (there are other ways not discussed here): Because you cannot
instantiate an object of type
ActionListener
, first you need 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
. You will create the
class
CalculateButtonHandler
to handle the event generated by clicking the button
calculateB
.
The
class
CalculateButtonHandler
is created on top of the
interface
ActionListener
. The definition of the
class
CalculateButtonHandler
is:
private class
CalculateButtonHandler
implements
ActionListener
//Line 1
{
public void
actionPerformed(ActionEvent e)
//Line 2
{
//The code for calculating the area and the perimeter
//and displaying these quantities goes here
}
}
Search WWH ::
Custom Search