(^384) | Event-Driven Input and Output
Figure 8.3 A Grid with Centered Headings in the First Row
is typically used to display a table of values, often with a text label at the top of each column
(called a column heading) that explains what the column contains. Figure 8.2 uses the column
headings “Format” and “Example.”
Alignment of Text Within Jlabels
By default, the text within a label begins at the left edge of the label. Sometimes, however,
we want to center the text within the label or have it appear as far to the right as possible
within the label. Java allows us to do so by providing a second argument when calling the
JLabelconstructor. This argument can be any of three predefined class constants provided
by the JLabelclass: JLabel.LEFT,JLabel.CENTER, or JLabel.RIGHT. For example, if we want the
column heading “Format” in Figure 8.2 to be centered, we would write
datePane.add(new Label("Format", JLabel.CENTER));
If instead we write
datePane.add(new Label("Format", JLabel.RIGHT));
then the text would be positioned as far to the right as possible within the label. Because the
usual position for text is toward the left, we rarely need to use JLabel.LEFT. Figure 8.3 shows
the result of centering the headings from the example in Figure 8.2.