ptg7068951
244 HOUR 17:Creating Interactive Web Programs
LISTING 17.3 The Full Text of WeightScale.java
1: importjava.awt.*;
2:
3: public classWeightScale extendsjavax.swing.JApplet {
4: floatlbs = 0F;
5: floatozs;
6: floatkgs;
7: floatmetricTons;
8: String name= “somebody”;
9:
10: public voidinit() {
11: String lbsValue = getParameter(“weight”);
12: if (lbsValue != null) {
13: lbs = Float.valueOf(lbsValue);
14: }
15: String personValue = getParameter(“person”);
16: if (personValue != null) {
17: name = personValue;
18: }
19: ozs = (float) (lbs * 16);
20: kgs = (float) (lbs / 2.204623);
21: metricTons= (float) (lbs / 2204.623);
22: }
23:
24: public voidpaint(Graphics screen) {
25: Graphics2D screen2D = (Graphics2D) screen;
26: screen2D.drawString(“Studying the weight of “+ name, 5, 30);
27: screen2D.drawString(“In pounds: “+ lbs, 55, 50);
28: screen2D.drawString(“In ounces: “+ ozs, 55, 70);
29: screen2D.drawString(“In kilograms: “+ kgs, 55, 90);
30: screen2D.drawString(“In metric tons: “+ metricTons, 55, 110);
31: }
32: }
Theinit()method is where the two parameters are loaded into the applet.
Because parameters come from the web page as strings, the weightparame-
ter must be converted to a floating-point number to use it in mathematical
expressions. The Floatobject class includes a valueOf(String)that returns
a string’s value as a Float. This value is automatically unboxed to the float
variable type in Line 13.
Lines 19–21 are used to convert the lbsvariable into different units of meas-
ure. Each statement has (float)in front of the conversion equation. This is
used to cast the result of the equation into a floating-point number.
The paint()method of the applet uses drawString()to display a line of
text. The paint()method has three arguments: the text to display, the x
position, and the y position where the text should be shown.