Java Reference
In-Depth Information
Now that the GUI is an object, we can write a separate client class to hold the
main method to construct it. The following short class does the job:
1 // Shows a BMI GUI on the screen.
2
3 public class RunBmiGui2 {
4 public static void main(String[] args) {
5 BmiGui2 gui = new BmiGui2(); // construct/show GUI
6 }
7 }
The advantage of an object-oriented GUI is that we can make it into an event lis-
tener. We want to add a listener to the Compute button to compute the user's BMI.
This listener will need to access the height and weight text fields and the central BMI
label. These components are fields within the BmiGui2 object, so if the BmiGui2
class itself implements ActionListener , it will have access to all the information it
needs.
Let's write a third version of our BMI GUI that handles action events. We'll
change our class name to BmiGui3 and change our class header to implement the
ActionListener interface:
public class BmiGui3 implements ActionListener {
To implement ActionListener , we must write an actionPerformed method. Our
actionPerformed code will read the two text fields' values, convert them into type
double , compute the BMI using the standard BMI formula of weight / height 2 * 703,
and set the text of the central BMI label to show the BMI result. The following code
implements the listener:
// Handles clicks on Compute button by computing the BMI.
public void actionPerformed(ActionEvent event) {
// read height and weight info from text fields
String heightText = heightField.getText();
double height = Double.parseDouble(heightText);
String weightText = weightField.getText();
double weight = Double.parseDouble(weightText);
// compute BMI and display it onscreen
double bmi = weight / (height * height) * 703;
bmiLabel.setText("BMI: " + bmi);
}
Now we have to attach the action listener to the Compute button. Since the GUI is
the listener, the parameter we pass to the button's addActionListener method is
Search WWH ::




Custom Search