Java Reference
In-Depth Information
are
mutually exclusive
—only
one
in the group can be selected at any time, just like the but-
tons on a car radio. We first discuss class
JCheckBox
.
The application of Figs. 12.17-12.18 uses two
JCheckBox
es to select the desired font style
of the text displayed in a
JTextField
. When selected, one applies a bold style and the other
an italic style. If
both
are selected, the style is bold
and
italic. When the application initially
executes, neither
JCheckBox
is checked (i.e., they're both
false
), so the font is plain. Class
CheckBoxTest
(Fig. 12.18) contains the
main
method that executes this application.
1
// Fig. 12.17: CheckBoxFrame.java
2
// JCheckBoxes and item events.
3
import
java.awt.FlowLayout;
4
import
java.awt.Font;
5
import
java.awt.event.ItemListener;
6
import
java.awt.event.ItemEvent;
7
import
javax.swing.JFrame;
8
import
javax.swing.JTextField;
9
import
javax.swing.JCheckBox;
10
11
public
class
CheckBoxFrame
extends
JFrame
12
{
13
private final
JTextField textField;
// displays text in changing fonts
14
private final
JCheckBox boldJCheckBox;
// to select/deselect bold
private final
JCheckBox italicJCheckBox;
// to select/deselect italic
15
16
17
// CheckBoxFrame constructor adds JCheckBoxes to JFrame
18
public
CheckBoxFrame()
19
{
20
super
(
"JCheckBox Test"
);
21
setLayout(
new
FlowLayout());
22
23
// set up JTextField and set its font
24
textField =
new
JTextField(
"Watch the font style change"
,
20
);
25
textField.setFont(
new
Font(
"Serif"
,
Font.PLAIN
,
14
));
26
add(textField);
// add textField to JFrame
27
28
boldJCheckBox =
new
JCheckBox(
"Bold"
);
29
italicJCheckBox =
new
JCheckBox(
"Italic"
);
30
add(boldJCheckBox);
// add bold checkbox to JFrame
31
add(italicJCheckBox);
// add italic checkbox to JFrame
32
33
// register listeners for JCheckBoxes
CheckBoxHandler handler =
new
CheckBoxHandler();
boldJCheckBox.addItemListener(handler);
italicJCheckBox.addItemListener(handler);
34
35
36
37
}
38
39
// private inner class for ItemListener event handling
40
private class
CheckBoxHandler
implements
ItemListener
41
{
Fig. 12.17
|
JCheckBox
es and item events. (Part 1 of 2.)