Java Reference
In-Depth Information
1
// Fig. 12.19: RadioButtonFrame.java
2
// Creating radio buttons using ButtonGroup and JRadioButton.
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.JRadioButton;
10
import
javax.swing.ButtonGroup;
11
12
public
class
RadioButtonFrame
extends
JFrame
13
{
14
private final
JTextField textField;
// used to display font changes
15
private final
Font plainFont;
// font for plain text
16
private final
Font boldFont;
// font for bold text
17
private final
Font italicFont;
// font for italic text
18
private final
Font boldItalicFont;
// font for bold and italic text
19
private final
JRadioButton plainJRadioButton;
// selects plain text
private final
JRadioButton boldJRadioButton;
// selects bold text
private final
JRadioButton italicJRadioButton;
// selects italic text
private final
JRadioButton boldItalicJRadioButton;
// bold and italic
private final
ButtonGroup radioGroup;
// holds radio buttons
20
21
22
23
24
25
// RadioButtonFrame constructor adds JRadioButtons to JFrame
26
public
RadioButtonFrame()
27
{
28
super
(
"RadioButton Test"
);
29
setLayout(
new
FlowLayout());
30
31
textField =
new
JTextField(
"Watch the font style change"
,
25
);
32
add(textField);
// add textField to JFrame
33
34
// create radio buttons
35
plainJRadioButton =
new
JRadioButton(
"Plain"
,
true
);
boldJRadioButton =
new
JRadioButton(
"Bold"
,
false
);
italicJRadioButton =
new
JRadioButton(
"Italic"
,
false
);
boldItalicJRadioButton =
new
JRadioButton(
"Bold/Italic"
,
false
);
36
37
38
39
add(plainJRadioButton);
// add plain button to JFrame
40
add(boldJRadioButton);
// add bold button to JFrame
41
add(italicJRadioButton);
// add italic button to JFrame
42
add(boldItalicJRadioButton);
// add bold and italic button
43
44
// create logical relationship between JRadioButtons
radioGroup =
new
ButtonGroup();
// create ButtonGroup
radioGroup.add(plainJRadioButton);
// add plain to group
radioGroup.add(boldJRadioButton);
// add bold to group
radioGroup.add(italicJRadioButton);
// add italic to group
radioGroup.add(boldItalicJRadioButton);
// add bold and italic
45
46
47
48
49
50
51
// create font objects
52
plainFont =
new
Font(
"Serif"
,
Font.PLAIN
,
14
);
53
boldFont =
new
Font(
"Serif"
,
Font.BOLD
,
14
);
Fig. 12.19
|
Creating radio buttons using
ButtonGroup
and
JRadioButton
. (Part 1 of 2.)