Java Reference
In-Depth Information
Table 3-21
Kilowatt Applet Constructed Components
OBJECT
IDENTIFIER
METHOD PARAMETER (CAPTION OR LENGTH)
Label
welcome
Welcome to the Appliance Energy Calculator
Label
costKwhrLabel
Please enter the cost per kilowatt-hour in cents:
TextField
costKwhrField
5
Label
hoursPerYearLabel
Please enter the kilowatt-hours consumed:
TextField
hoursPerYearField
5
Button
calcButton
Calculate
Label
outputLabel
Click the Calculate button to display the
average energy cost.
6. Create an init() method to add all of the above components to the applet
interface.
7. Enter the code to add the ActionListener to the calcButton and close the
init() method with a brace.
8. Create an actionPerformed() method to convert the input and perform the
calculations. Enter the code to get the text from each text box, parse it, and
assign it to the appropriate declared variable as shown in Table 3-22.
Table 3-22
KilowattApplet Construction and Conversion Code
double costKwhr = Double.parseDouble(costKwhrField.getText());
double kwHours = Double.parseDouble(hoursPerYearField.getText());
9. Declare a double variable named average.
10. Write a line of code to perform the calculation that multiplies the cents by
the kilowatt-hours in a year and then assigns it to the variable, average.
11. Enter the code from Table 3-23 to round the average with the Math.round()
method and assign it to the text of the output label. The Math.round()
method includes a casting of the literal 100 to double in order to retain the
decimal places.
Table 3-23
KilowattApplet Output Code
outputLabel.setText(“The average annual cost to operate this appliance is $” +
Math.round(average* 100)/100D);
(continued)
 
Search WWH ::




Custom Search