Java Reference
In-Depth Information
Obviously, the advantage is that it becomes easy to reuse the same listener class (and instances,
even) across different components. The downside is that this requires a little more effort to
set up.
So far, you've only seen the ActionListener for a JButton . A wealth of other listeners
exists as well. The general usage is always the same: construct a listener with the appropri-
ate type using one of the three techniques seen previously, and then add it to a component using
addLISTENERTYPEListener . A nonexhaustive list of some of the interesting listeners is included in
the following table.
listener (interface): method
to add
can Be used With: purpose
method(s) to implement
Action Listener
(ActionListener) -
addActionListener
Fires ActionEvent when user per-
forms primary action on component.
Can be used with JButton ,
JCheckBox , JComboBox ,
JRadioButton , and
JTextField .
actionPerformed : Code that
reacts to the action.
Caret Listener
(CaretListener) -
addCaretListener
Fires CaretEvent whenever the
caret (the cursor in a text field,
for instance) moves or when the
selection changes.
Can be used with JTextArea ,
JTextField , and JTextPane .
caretUpdate : Code that reacts
whenever caret is updated (is
moved, the selection changes,
text is inserted, and so on).
Change Listener
(ChangeListener) -
addChangeListener
Fires ChangeEvent whenever a
component changes its state.
stateChanged : Code that reacts
to component changes.
Can be used with JButton ,
JCheckBox , JProgressBar , and
JRadioButton . Also useful with
JSlider and JSpinner , as these
will fire events for the value of
the slider or the spinner changes.
These two components do not
accept ActionListeners , so
here you'll want to use Change
Listeners.
Item Listener
(ItemListener) -
addItemListener
Fires ItemEvent whenever a
state change occurs in the com-
ponent's items.
JCheckBox , JComboBox , and
other components keep a list of
items that accept this listener.
itemStateChanged : Code
that reacts when state of items
changes.
Search WWH ::




Custom Search