Java Reference
In-Depth Information
To group radio buttons, you need to create an instance of
java.swing.ButtonGroup
and use the
add
method to add them to it, as follows:
ButtonGroup group =
new
ButtonGroup();
group.add(jrb1);
group.add(jrb2);
This code creates a radio-button group for the radio buttons
jrb1
and
jrb2
so that they are
selected mutually exclusively. Without grouping,
jrb1
and
jrb2
would be independent.
Note
ButtonGroup
is not a subclass of
java.awt.Component
, so a
ButtonGroup
object cannot be added to a container.
To see if a radio button is selected, use the
isSelected()
method.
GUI helper class
12.32
How do you create a radio button? How do you create a radio button with the button
selected initially? How do you group radio buttons together? How do you determine
whether a radio button is selected?
✓
✓
Check
Point
To create a label, use the
JLabel
class.
Key
Point
A
label
is a display area for a short text, an image, or both. It is often used to label other
components (usually text fields). Figure 12.24 lists the constructors and methods in the
JLabel
class.
javax.swing.JComponent
The
get
and
set
methods for these data fields are provided
in the class, but omitted in the UML diagram for brevity.
javax.swing.JLabel
-text: String
-icon: javax.swing.Icon
-horizontalAlignment: int
-horizontalTextPosition: int
-verticalAlignment: int
-verticalTextPosition: int
-iconTextGap: int
+JLabel()
+JLabel(icon: javax.swing.Icon)
+JLabel(icon: Icon, hAlignment: int)
+JLabel(text: String)
+JLabel(text: String, icon: Icon,
hAlignment: int)
+JLabel(text: String, hAlignment: int)
The label's text.
The label's image icon.
The horizontal alignment of the text and icon on the label.
The horizontal text position relative to the icon on the label.
The vertical alignment of the text and icon on the label.
The vertical text position relative to the icon on the label.
The gap between the text and the icon on the label.
Creates a default label without any text or icons.
Creates a label with an icon.
Creates a label with an icon and the specified horizontal alignment.
Creates a label with text.
Creates a label with text, an icon, and the specified horizontal alignment.
Creates a label with text and the specified horizontal alignment.
F
IGURE
12.24
JLabel
displays text or an icon, or both.
JLabel
inherits all the properties from
JComponent
and has many properties similar to the
ones in
JButton
, such as
text
,
icon
,
horizontalAlignment
,
verticalAlignment
,
horizontalTextPosition
,
verticalTextPosition
, and
iconTextGap
. For example,
the following code displays a label with text and an icon: