Java Reference
In-Depth Information
ActionEvent
this does not make sense. It is not of importance where a button
was pressed. An
ActionEvent
on the other hand contains information on which
button had been pressed. The different event types supply methods to access the
information contained in the event, e.g.
getX()
and
getY()
allow one to get the co-
ordinates of a
MouseEvent
, and
getActionCommand()
allows one to find the source
of an action event.
9.2
■
Implementing listeners
We have so far implemented listeners in classes of their own. We now see
three more ways of implementing them. We return to our first GUI, the counter
from Chapter 3. There, a class
CounterListener
is defined that implements an
ActionListener
.Weillustrate the other methods for implementing listeners on
this example.
9.2.1
Listeners as internal classes
In the counter example we defined the listener in a separate class
CounterLis-
tener
. The listener is assigned to two buttons and has to take actions when one
of them is pressed. The reaction was to update the
CounterPanel
. The counter
listener has to know
which
panel to update. Therefore we pass a reference to a
CounterPanel
in the constructor of the listener. Alternatively we can define the
listener as an
internal class
inside
CounterPanel
. Then the methods of
Counter-
Panel
are known to the listener and can be called directly, i.e. the listener can use
decrement()
instead of
countPane.decrement()
. Therefore, no reference to a
panel is passed to the listener. The constructor of the listener has an empty body. In
fact, it can be omitted altogether; then the default constructor of
ActionListener
takes over. This is implemented in the package
its.CounterInternalGUI
, where
the class
CounterInternalPanel
with an internally defined listener replaces both
CounterPanel
and
CounterListener
.Weonly print the listing of this class.
File:
its/CounterInternalGUI/CounterInternalPanel.java
1.
package
its.CounterInternalGUI;
2.
3.
import
javax.swing.JPanel;
4.
import
javax.swing.JButton;
5.
import
javax.swing.JLabel;
6.
import
java.awt.BorderLayout;
import
javax.swing.SwingConstants;
7.
import
java.awt.event.ActionListener;
8.
import
java.awt.event.ActionEvent;
9.
10.
11.
public class
CounterInternalPanel
extends
JPanel {
12.
13.
private
CounterModel counter;
Search WWH ::
Custom Search