Java Reference
In-Depth Information
This class has one method; Line 2 is the first statement of that method. Let us look at the
statement in Line 4:
length = Double.parseDouble(lengthTF.getText());
The length of the rectangle is stored in the text field
lengthTF
. We use the method
getText
to retrieve the string from this text field, specifying the length. Now the value
of the expression
lengthTF.getText()
is the length, but it is in a string form. So we
need to use the method
parseDouble
to convert the length string into an equivalent
decimal number. The length is then stored in the variable
length
. The statement in Line
5 works similarly for the width.
The statements in Lines 6 and 7 compute the area and the perimeter, respectively. The
statement in Line 8 uses the method
setText
of the
class
JTextField
to display the area.
Because
setText
requires that the argument be a string, you need to convert the value of the
variable
area
into a string. The easiest way to do this is to concatenate the value of
area
to
an empty string. Similar conventions apply for the statement in Line 9.
It follows that the method
actionPerformed
displays the area and perimeter in the
corresponding
JTextFields
.
Before creating an action listener for the
JButton exitB
, let us summarize what we've
done so far to create and register an action event listener:
1. Created a class that implements the
interface
ActionListener
. For
example, for the
JButton calculateB
we created the
class
CalculateButtonHandler
.
2. Provided the definition of the method
actionPerformed
within the
class that you created in Step 1. The method
actionPerformed
con-
tains the code that the program executes when a specific event is
generated. For example, when you click the
JButton calculateB
,
the program should calculate and display the area and perimeter of the
rectangle.
3. Created and instantiated an object of the class type created in Step 1. For
example,
6
for
the
JButton calculateB
we created the object
cbHandler
.
4. Registered the event handler created in Step 3 with the object that
generates an action event using the method
addActionListener
. For
example, for
JButton calculateB
the following statement registers the
object
cbHandler
to listen and register the action event:
calculateB.addActionListener(cbHandler);
Search WWH ::
Custom Search