Java Reference
In-Depth Information
Setting Up Components
When you make a class an event listener, you have set up a specific type of event to be
heard by that class. However, the event won't actually be heard unless you follow up
with a second step: A matching listener must be added to the component. That listener
generates the events when the component is used.
After a component is created, you can call one of the following methods on the compo-
nent to associate a listener with it:
addActionListener()
—
JButton
,
JCheckBox
,
JComboBox
,
JTextField
,
JRadioButton
, and
JMenuItem
components
n
addFocusListener()
—All Swing components
n
addItemListener()
—
JButton
,
JCheckBox
,
JComboBox
, and
JRadioButton
compo-
nents
n
addKeyListener()
—All Swing components
n
addMouseListener()
—All Swing components
n
addMouseMotionListener()
—All Swing components
n
addTextListener()
—
JTextField
and
JTextArea
components
n
addWindowListener()
—
JWindow
and
JFrame
components
n
CAUTION
Modifying a component after adding it to a container is an easy
mistake to make in a Java program. You must add listeners to a
component and handle any other configuration before the compo-
nent is added to any containers; otherwise, these settings are dis-
regarded when the program is run.
12
The following example creates a
JButton
object and associates an action event listener
with it:
JButton zap = new JButton(“Zap”);
zap.addActionListener(this);
All the listener adding methods take one argument: the object that is listening for events
of that kind. Using
this
indicates that the current class is the event listener. You could
specify a different object, as long as its class implements the right listener interface.