Java Reference
In-Depth Information
Notice the following:
The
class
CalculateButtonHandler
starts with the modifier
private
. This is because you want this class to be used only within
your
RectangleProgram
.
This class uses another modifier,
implements
. This is how you build
classes on top of classes that are interfaces. Notice that you have not yet
provided the code for the method
actionPerformed
. You will do that
shortly.
In Java,
implements
is a reserved word.
Next, we illustrate how to create a listener object of type
CalculateButtonHandler
.
Consider the following statements:
CalculateButtonHandler cbHandler;
cbHandler =
new
CalculateButtonHandler();
//instantiate the object
As described, these statements create the listener object. Having created a listener, you
next must associate (or in Java terminology, register) this handler with the corresponding
JButton
. The following line of code registers
cbHandler
as the listener object of
calculateB
:
calculateB.addActionListener(cbHandler);
The complete definition of the
class
CalculateButtonHandler
, including the code
for the method
actionPerformed
, is:
private class
CalculateButtonHandler
implements
ActionListener
//Line 1
{
public void
actionPerformed(ActionEvent e)
//Line 2
{
double
width, length, area, perimeter;
//Line 3
length
= Double.parseDouble(lengthTF.getText());
//Line 4
width
= Double.parseDouble(widthTF.getText());
//Line 5
area = length * width;
//Line 6
perimeter = 2 * (length + width);
//Line 7
areaTF.setText("" + area);
//Line 8
perimeterTF.setText("" + perimeter);
//Line 9
}
}
In the preceding program segment, Line 1 declares the
class
CalculateButtonHandler
and makes it an action listener by including the phrase
implements
ActionListener
. Note that all of this code is just a new class definition.
Search WWH ::
Custom Search