Java Reference
In-Depth Information
•
addKeyListener()
•
addMouseListener()
•
addMouseMoveListener()
•
addMouseTrackListener()
•
addPaintListener()
•
addTraverseListener()
There are others. SWT naming conventions define an interface for
which each
add...Listener()
method is named. For example, there is a
SelectionListener
interface. Many such interfaces have multiple methods,
each to handle a distinct kind of event; for example, the
MouseListener
inter-
face defines separate methods to handle a button down event, a button release
event, and a double-click event. As in Swing, it is common to implement event
listeners as anonymous inner classes that implement the listener interface.
However, since it is common to be interested only in some (or even only one)
listener event, it is annoying to have to implement the full interface, since you
have to provide method implementations for every event. For this reason, SWT
also provides classes called
adapters
that implement “do-nothing” methods for
every listener event. These also follow a naming convention. For example, the
adapter for the
MouseListener
interface is a class named
MouseAdapter
; the
SelectionListener
interface has an adapter named
SelectionAdapter
,
and so on.
For us, this means that we are going to create a reference to an anonymous
inner class that implements the
SelectionListener
interface by extending
the
SelectionAdapter
class. This is probably the weirdest common code
construct in Java. Let's take a direct look at that method (Example 17.2).
If you can correctly answer the following question, then you can be reason-
ably assured that you do, in fact, understand what is going on here. Would the
program compile and run correctly if the type of the
upAction
variable were
changed to
SelectionAdapter
? The answer is in the footnote.
14
14. Yes, it would. The reason is that the
addSelectionListener()
method takes an argu-
ment of type
SelectionListener
. Both
SelectionListener
and
SelectionAdapter
are of that base type. Aren't
Object
s wonderful?