Java Reference
In-Depth Information
The applet version of the Body Mass Index Calculator now is complete. You
added the import statements, changed the name of the class to BodyMassApplet,
and constructed the applet components. You then entered code for the init()
method. Next, you included the actionPerformed() method to convert the text to
numbers, calculate, and display the answer. Finally, you coded the paint()
method to display the company logo in the Applet Viewer window.
Figure 3-47 shows the applet code in its entirety. Check your own code for
syntax, proper spelling, capitalization, and indentations. Your lines may wrap
differently. When you are confident that everything is correct, you are ready to
save and compile your program.
1
/*
2
Chapter 3: The Body Mass Index Calculator
3
Programmer: J. Starks
4
Date:
October 20, 2007
5
Filename:
BodyMassApplet.java
6
Purpose:
This project calculates the body mass index based
7
on a person's height and weight.
8
*/
9
10
import
java.applet.*;
11
import
java.awt.*;
12
import
java.awt.event.*;
13
14
public class
BodyMassApplet
extends
Applet
implements
ActionListener
15
{
16
//declare variables
17
Image
logo;
//declare an Image object
18
int
inches, pounds;
19
double
meters, kilograms, index;
20
21
//construct components
22
Label
companyLabel =
new
Label
(
"THE SUN FITNESS CENTER BODY MASS INDEX CALCULATOR"
)
;
23
Label
heightLabel =
new
Label
(
"Enter your height to the nearest inch: "
)
;
24
TextField
heightField =
new
TextField
(
10
)
;
25
Label
weightLabel =
new
Label
(
"Enter your weight to the nearest pound: "
)
;
26
TextField
weightField =
new
TextField
(
10
)
;
27
Button
calcButton =
new
Button
(
"Calculate"
)
;
28
Label
outputLabel =
new
Label
(
"Click the Calculate button to see your body mass index."
)
;
29
30
public void
init
()
31
{
32
setForeground
(
Color
.red
)
;
33
add
(
companyLabel
)
;
34
add
(
heightLabel
)
;
35
add
(
heightField
)
;
36
add
(
weightLabel
)
;
37
add
(
weightField
)
;
38
add
(
calcButton
)
;
39
calcButton.addActionListener
(
this
)
;
40
add
(
outputLabel
)
;
41
logo = getImage
(
getDocumentBase
()
,
"logo.gif"
)
;
42
}
43
44
public void
actionPerformed
(
ActionEvent
e
)
45
{
46
47
inches =
Integer
.parseInt
(
heightField.getText
())
;
48
pounds =
Integer
.parseInt
(
weightField.getText
())
;
49
meters = inches / 39.36;
50
kilograms = pounds / 2.2;
51
index = kilograms /
Math
.pow
(
meters,2
)
;
52
outputLabel.setText
(
"YOUR BODY MASS INDEX IS "
+
Math
.round
(
index
)
+
"."
)
;
53
}
54
55
public void
paint
(
Graphics
g
)
56
{
57
g.drawImage
(
logo,125,160,
this
)
;
58
}
59
}
FIGURE 3-47
Search WWH ::
Custom Search