Java Reference
In-Depth Information
// Create an image icon from an image file
ImageIcon icon =
new
ImageIcon(
"image/grapes.gif"
);
// Create a label with a text, an icon,
// with centered horizontal alignment
JLabel jlbl =
new
JLabel(
"Grapes"
, icon, JLabel.CENTER);
//Set label's text alignment and gap between text and icon
jlbl.setHorizontalTextPosition(JLabel.CENTER);
jlbl.setVerticalTextPosition(JLabel.BOTTOM);
jlbl.setIconTextGap(
5
);
12.33
How do you create a label named
Address
? How do you change the name on a
label? How do you set an icon in a label?
12.34
Given a
JLabel
object
jlblMap
, write statements to set the label's foreground to
red
, background to
yellow
, mnemonic to
M
, tool tip text to
Map image
, horizontal
alignment to
RIGHT
, vertical alignment to
BOTTOM
, horizontal text position to
LEFT
,
vertical text position to
TOP
, and icon text gap to
5
.
✓
✓
Check
Point
To create a text field, use the
JTextField
class.
Key
Point
A
text field
can be used to enter or display a string.
JTextField
is a subclass of
JTextComponent
. Figure 12.25 lists the constructors and methods in
JTextField
.
The
get
and
set
methods for these data fields are provided
in the class, but omitted in the UML diagram for brevity.
javax.swing.text.JTextComponent
-text: String
-editable: boolean
The text contained in this text component.
Indicates whether this text component is editable (default: true).
javax.swing.JTextField
-columns: int
-horizontalAlignment: int
+JTextField()
+JTextField(column: int)
+JTextField(text: String)
+JTextField(text: String, columns: int)
The number of columns in this text field.
The horizontal alignment of this text field (default: LEFT).
Creates a default empty text field with number of columns set to 0.
Creates an empty text field with a specified number of columns.
Creates a text field initialized with the specified text.
Creates a text field initialized with the specified text and columns.
F
IGURE
12.25
JTextField
enables you to enter or display a string.
JTextField
inherits
JTextComponent
, which inherits
JComponent
. Here is an exam-
ple of creating a text field with red foreground color and right horizontal alignment:
JTextField jtfMessage =
new
JTextField(
"T-Storm"
);
jtfMessage.setForeground(Color.RED);
jtfMessage.setHorizontalAlignment(JTextField.RIGHT);
To set new text in a text field, use the
setText(newText)
method. To get the text from a text
field, use the
getText()
method.