Java Reference
In-Depth Information
BodyMassSwing.java
10/9/2007
1 /*
2
Chapter 3: The Body Mass Index Calculator
3
Programmer: J. Starks
4
Date:
October 20, 2007
5
Filename:
BodyMassSwing.java
6
Purpose:
This project calculates the body mass index based
7
on a person's height and weight.
8 */
9
10 import javax.swing.JOptionPane;
11
12 public class BodyMassSwing
13 {
14
long text
lines wrap to
next line of
printout
public static void main ( String [] args )
15
{
16
// declare and construct variables
17
String height, weight;
18
int inches, pounds;
19
double kilograms, meters, index;
20
21
// print prompts and get input
22
System .out.println ( "\tTHE SUN FITNESS CENTER BODY MASS INDEX CALCULATOR" ) ;
23
height=JOptionPane.showInputDialog ( null ,
"Enter your height to the nearest inch: " ) ;
24
inches = Integer .parseInt ( height ) ;
25
weight=JOptionPane.showInputDialog ( null ,
"Enter your weight to the nearest pound: " ) ;
26
pounds = Integer .parseInt ( weight ) ;
27
28
// calculations
29
meters = inches / 39.36;
30
kilograms = pounds / 2.2;
31
index = kilograms / Math .pow ( meters,2 ) ;
32
33
// output
34
JOptionPane.showMessageDialog ( null , "YOUR BODY MASS INDEX IS " + Math .round (
index ) + "." , "Body Mass Calculator" ,JOptionPane.PLAIN_MESSAGE ) ;
35
36
System .exit ( 0 ) ;
37
}
38 }
FIGURE 3-36
Moving to the Web
The final version of the program for the Body Mass Index Calculator is to create
an applet. Recall that an applet is a program called from within another environ-
ment, usually a Web page. In order to convert the Body Mass Index Calculator
from a console application that runs in the command prompt window to an
applet that will display as part of a Web page, you will need to create four kinds
of objects: an Image, Labels, TextFields, and Buttons.
In Chapter 2, you learned that an applet uses different Java packages than an
application and thus must import the java.awt and java.applet class packages
needed to support the applet-related methods. Recall that applets also must
extend the Applet class in the class header in order to inherit attributes from the
applet package.
Implementing an ActionListener to Handle Events
Because the Body Mass Index Calculator applet will be interactive, the
program must have the ability to handle events. Every time the user clicks a
button, presses a key on the keyboard, or opens a program window, for example,
an event occurs. The event classes are included in the java.awt.event package ,
which provides interfaces and classes for dealing with different types of events
Search WWH ::




Custom Search