Java Reference
In-Depth Information
36 frame.add(north, BorderLayout.NORTH);
37 frame.add( new JTextArea(), BorderLayout.CENTER);
38 frame.add(south, BorderLayout.SOUTH);
39
40 frame.setVisible( true );
41 }
42 }
14.3 Interaction Between Components
In this section we'll write some larger and more complex graphical programs. These
programs will raise new issues about communication between components and event
listeners.
Example 1: BMI GUI
Consider the task of writing a graphical program to compute a person's body mass
index (BMI). The program should have a way for the user to type in a height and a
weight and should use these values to compute the person's BMI. A reasonable
appearance for the GUI would be the following window, which uses text fields for
input and a button to trigger a computation of the BMI:
Let's figure out how to create a GUI with the proper components and layout first
and worry about event handling later. Since we want the program to display text
fields with labels next to them, aligned in a row/column format, a 2
2 GridLayout is
a good choice. But we'll want to use a composite layout, because we don't want the
central label and the Compute button to have the same size and position as the grid
squares. We'll use a BorderLayout on our frame and add the central “Type your
height and weight” label and Compute button directly to it. We'll also create a panel
with a 2
×
2 GridLayout and place it in the north region of the frame.
The code that follows implements the initial BMI user interface. The program sets
the frame's title by passing it as a parameter to its constructor:
×
1 // A GUI to compute a person's body mass index (BMI).
2 // Initial version without event handling.
3
4 import java.awt.*;
 
Search WWH ::




Custom Search