Java Reference
In-Depth Information
Swing provides many GUI components for developing a comprehensive user interface.
Key
Point
Previous chapters briefly introduced
JButton
,
JCheckBox
,
JRadioButton
,
JLabel
,
JTextField
, and
JPasswordField
. This chapter introduces in detail how the events are
processed for these components. We will also introduce
JTextArea
,
JComboBox
,
JList
,
JScrollBar
, and
JSlider
. More GUI components such as
JMenu
,
JToolBar
,
JTabbedPane
,
JSplitPane
,
JSpinner
,
JTree
, and
JTable
will be introduced in bonus
Web Chapters 36-40.
JTextField
A GUI component may fire many types of events.
ActionEvent
is commonly
processed for
JCheckBox
,
JRadioButton
, and
JTextField
, and
ItemEvent
can
be used for
JCheckBox
and
JRadioButton
.
In the previous chapter, you learned how to handle an action event for
JButton
. This section
introduces handling events for check boxes, radio buttons, and text fields.
When a
JCheckBox
or a
JRadioButton
is clicked (that is, checked or unchecked), it
fires an
ItemEvent
and then an
ActionEvent
. When you press the
Enter
key on a
JTextField
, it fires an
ActionEvent
.
Listing 17.1 gives a program that demonstrates how to handle events from check boxes,
radio buttons, and text fields. The program displays a label and allows the user to set the col-
ors of the text in the label using radio buttons, set fonts using check boxes, and set new text
entered from a text field, as shown in Figure 17.1.
Key
Point
JPanel
with
BorderLayout
for
a label and a text field
F
IGURE
17.1
The program demonstrates check boxes, radio buttons, and text fields.
L
ISTING
17.1
GUIEventDemo.java
1
import
java.awt.*;
2
import
java.awt.event.*;
3
import
javax.swing.*;
4
import
javax.swing.border.*;
5
6
public class
GUIEventDemo
extends
JFrame {
7
private
JLabel jlblMessage =
new
JLabel(
"Hello"
, JLabel.CENTER);
create label
8
9
// Create check boxes to set the font for the message
10
private
JCheckBox jchkBold =
new
JCheckBox(
"Bold"
);
create check boxes
11
private
JCheckBox jchkItalic =
new
JCheckBox(
"Italic"
);
12
13
// Create three radio buttons to set message colors
14
private
JRadioButton jrbRed =
new
JRadioButton(
"Red"
);
create radio buttons
15
private
JRadioButton jrbGreen =
new
JRadioButton(
"Green"
);
16
private
JRadioButton jrbBlue =
new
JRadioButton(
"Blue"
);
17
18
// Create a text field for setting a new message