241
Sams.net Learning Center
abcd
13
P2/V4sqc 7 TY Java in 21 Days 030-4 sdv 12.22.95
Ch 13 LP#3
In this section, you'll learn about the basic UI components: labels, buttons, checkboxes, choice
menus, and text fields. In each case, the procedure for creating the component is the same--you
first create the component, and then add it to the panel that holds it, at which point it is displayed
on the screen. To add a component to a panel (such as your applet, for example), use the
add
()
method:
public void init() {
Button b = new Button("OK");
add(b);
}
Note that where the component appears in the panel depends on the layout that panel is defined
to have. The default layout for panels such as applets is
FlowLayout
, with a centered alignment,
which means that components are added from left to right in rows, and then row by row as they
fit, with each row centered. This explains why some of the examples in this section look a little
funny. You'll learn more about panels and layouts in the next section.
Note also that each of these components has an action associated with it--that is, something that
component does when it's activated. Actions generally trigger events or other activities in your
applet (often called callbacks in other window toolkits). In this section, you'll focus on creating
the components themselves; you'll learn about adding actions to them later in today's lesson.
On to the components!
Labels
The simplest form of UI component is the label.
Labels are, effectively, text strings that you can use to label other UI components.
The advantages that a label has over an ordinary text string is that it follows the layout of the given
panel, and you don't have to worry about repainting it every time the panel is redrawn. Labels
also can be easily aligned within a panel, enabling you to attach labels to other UI components
without knowing exact pixel positions.
To create a label, use one of the following constructors:
s
s
Label()
creates an empty label, with its text aligned left.
s
s
Label(String)
creates a label with the given text string, also aligned left.
s
s
Label(String, int)
creates a label with the given text string and the given alignment.
The available alignments are stored in class variables in
Label
, making them easier to
remember:
Label.RIGHT
,
Label.LEFT
, and
Label.CENTER
.
The label's font is determined by the overall font for the component (as set by the
setFont
()
method).
NEW
TERM
030-4s CH13.i
1/29/96, 10:33 PM
241