Java Applet Basics (2)
The Body Mass Index Calculator
The Applet Skeleton import java.applet.*; import java.awt.*; public class BodyMassApplet extends Applet { }
The HTML Page
Create the Skeleton Files
Control Components Label TextField Button
Add a Label Control import java.applet.*; import java.awt.*; public class BodyMassApplet extends Applet { Label myLabel = new Label(“XXXXXXXX”); public void init() { add(myLabel); }
Member Variable
Add Labels into the Skeleton
Add a TextField Control import java.applet.*; import java.awt.*; public class BodyMassApplet extends Applet { TextField myTextField = new TextField(columns); public void init() { add(myTextField); }
Add TextFields into the Skeleton
Add a Button Control import java.applet.*; import java.awt.*; public class BodyMassApplet extends Applet { Button myButton = new Button(“Text on the Button”); public void init() { add(myButton); }
Add Buttons into the Skeleton
Handle Action Events import java.awt.event.*; public class BodyMassApplet extends Applet implements ActionListener { Button myButton = new Button(“my button”); public void init() { add(myButton); myButton.addActionListener(this); } public void actionPerformed(ActionEvent e) { //handle the event here }
Add the Event Handler
Display Text on a Label Control Syntax: myLabel.setText(“the text shown on the label control”);
Read Text from a TextField Syntax: myTextField.getText(); E.g. String input; input = myTextField.getText();
Read Inputs From all TextFields
Math.round(dbl) Rounds a real number into the nearest integer Syntax: integer = Math.round(dbl) Example: double dblIndex; int intIndex; intIndex = Math.round(dblIndex); Question: what’s the difference between Math.round(dbl) and (int)dbl?
Round the Body Index