Java Reference
In-Depth Information
the GUI itself. Because this code is inside the GUI object's constructor, we pass the
GUI as a parameter using the keyword
this
:
// attach GUI as event listener to Compute button
computeButton.addActionListener(this);
The second version of our BMI GUI used a separate class called
RunBmiGui2
as a
client to run the GUI. However, using a second class for such a minimal client pro-
gram is a bit of a waste. It is actually legal to place the
main
method in the BMI GUI
class itself and not use the
RunBmiGui2
class. If we do this, the class becomes its
own client, and we can just compile and run the GUI class to execute the program.
(Static methods like
main
are generally placed above any fields, constructors, and
instance methods in the same file.)
After we implement the listener code and incorporate the
main
method, the BMI
GUI program is complete:
1 // A GUI to compute a person's body mass index (BMI).
2 // Final version with event handling.
3
4
import
java.awt.*;
5
import
java.awt.event.*;
6
import
javax.swing.*;
7
8
public class
BmiGui3
implements
ActionListener {
9 // BmiGui3 is its own runnable client program
10
public static void
main(String[] args) {
11 BmiGui3 gui =
new
BmiGui3();
12 }
13
14 // onscreen components stored as fields
15
private
JFrame frame;
16
private
JTextField heightField;
17
private
JTextField weightField;
18
private
JLabel bmiLabel;
19
private
JButton computeButton;
20
21
public
BmiGui3() {
22 // set up components
23 heightField =
new
JTextField(5);
24 weightField =
new
JTextField(5);
25 bmiLabel =
new
JLabel("Type your height and weight");
26 computeButton =
new
JButton("Compute");
27
28 // attach GUI as event listener to Compute button
Search WWH ::
Custom Search