Java Reference
In-Depth Information
Consider the statements:
JLabel lengthL;
lengthL = new JLabel("Enter the length:", SwingConstants.RIGHT);
After these statements execute, the label in Figure 6-5 is created.
FIGURE 6-5 JLabel with the text Enter the length:
Now consider the following statements:
6
private JLabel lengthL, widthL, areaL, perimeterL;
//Line 1
lengthL =
new JLabel("Enter the length: ", SwingConstants.RIGHT); //Line 2
widthL =
new JLabel("Enter the width: ", SwingConstants.RIGHT);
//Line 3
areaL = new JLabel("Area: ", SwingConstants.RIGHT);
//Line 4
perimeterL =
new JLabel("Perimeter: ", SwingConstants.RIGHT); //Line 5
The statement in Line 1 declares four reference variables, lengthL , widthL , areaL , and
perimeterL , of the JLabel type. The statement in Line 2 instantiates the object
lengthL , assigns it the title Enter the length: , and sets the title alignment to right-
justified. The statements in Lines 3 through 5 instantiate the objects widthL , areaL , and
perimeterL with appropriate titles and text alignment.
Next, we add these labels to the pane declared at the beginning of this section. The
following statements accomplish this. (Recall from the preceding section that we use the
method add to add components to a pane .)
pane.add(lengthL);
pane.add(widthL);
pane.add(areaL);
pane.add(perimeterL);
Because we have specified a grid layout for the pane with four rows and one column, the
label lengthL is added to the first row, the label widthL is added to the second row, and
so on.
Now that you know how to add the components to the pane , you can put together
the
program to create
these
labels. RectangleProgramTwo builds on the
Search WWH ::




Custom Search