Java Reference
In-Depth Information
17.2.1
JButtons
As shown in Fig. 17.3, an instance of class
JButton
is a component that can be
placed in a
JFrame
. The creation of a new
JButton
is easy; the argument of the
constructor in a new-expression is the string to be displayed on the button, e.g.:
A footnote on
top of lesson
page 17.2 gives
more detail.
new
JButton("Yeeaaah")
JButton
is a subclass of the older class
Button
of package
java.awt
, and
you can create
Buttons
as well:
Get a class that
creates buttons
from a footnote
on 17.2.
new
Button("Nyaaaah")
and place them in the content pane of the
JFrame
.
A
JButton
and a
Button
look slightly different, as you can see in a foot-
note near the top of lesson page 17.2.
17.2.2
JLabels, JTextFields, JTextAreas
Putting labels into a JFrame
An instance of class
JLabel
is a component that is a short text, an image, or
both. In this text, we deal only with
JLabel
s that are text. As you know from Sec.
17.1, the argument of a
JLabel
constructor is the text that is to be displayed.
Here is an example:
Activity 17-2.2
Get a class that
creates labels
from a footnote.
JLabel label=
new
JLabel("top label");
If a window is resized by dragging, as activity 17.2.2 shows, a label may be
partially obscured. Of course, you can drag to make the window bigger.
Retrieve and change the text in a label using
getText
and
setText
, e.g.
String s= label.getText();
label.setText("new text");
Labels are left-adjusted by default, but you can center or right-adjust them.
For example, use this call to right-adjust the label:
label.setHorizontalAlignment(SwingConstants.RIGHT);
The constants of class
SwingConstants
that can be used as the argument
are:
LEFT
,
CENTER
,
RIGHT
,
LEADING
, and
TRAILING
.
Change the vertical alignment using a call like the following. Possible argu-
ments are these constants of
SwingConstants
:
TOP
,
CENTER
, and
BOTTOM
.
label.setVerticalAlignment(SwingConstants.TOP);
Putting text fields into a JFrame
An instance of class
JTextField
is a component that is a one-line field into
which the user can type text. It is often called simply a
text field
. An example of
a
JTextField
appears in the north part of the content pane of Fig. 17.2.
Search WWH ::
Custom Search