Java Reference
In-Depth Information
interface has seven methods, we must implement all seven methods, even
though we are interested in only one of the seven methods.
One can imagine the messy code that will ensue when a large program
handles numerous events. The problem is that every event-handling strategy
corresponds to a new class, and it would be bizarre to have many classes with
lots of methods that simply declare
{ }
.
As a result, the
java.awt.event
package defines a set of
listener adapter
classes
. Each listener interface that has more than one method is implemented
by a corresponding listener adapter class, with empty bodies. Thus instead of
providing the empty bodies ourselves, we can simply extend the adapter class
and override the methods we are interested in. In our case, we need to extend
WindowAdapter
. This gives the (flawed) implementation for
CloseableFrame
,
shown in Figure B.12.
The code in Figure B.12 fails because multiple implementation inherit-
ance is illegal in Java. This is not a serious problem, however, because we do
not need the
CloseableFrame
to be the object that handles its own events.
Instead, it can be delegated to a function object.
Figure B.13 illustrates this approach. The
ExitOnClose
class implements
the
WindowListener
interface by extending
WindowAdapter
. An instance of that
class is created and registered as the frame's window listener.
ExitOnClose
is
declared as an inner class instead of a nested class. This would give it access
to any of the
CloseableFrame
's instance members, should it need it. The event-
handling model is a classic example of the use of function objects and is the
reason that inner classes were deemed an essential addition to the language
(recall that inner classes and the new event model appeared simultaneously in
Java 1.1).
Figure B.14 shows the logical continuation, using anonymous inner
classes. Here we are adding a
WindowListener
and explaining, on pretty much
the next line of code, what the
WindowListener
does. This is a classic use of the
anonymous inner classes. The pollution of braces, parentheses, and semicolons
The
listener adapter
classes
provide
default implemen-
tations of all the
listener methods.
figure B.12
CloseableFrame
class
using
WindowAdapter
.
This does not work
because there is no
multiple inheritance in
Java.
1
// Frame that closes on a window-close event: (flawed)
2
public class CloseableFrame extends JFrame, WindowAdapter
3
{
4
public CloseableFrame( )
5
{ addWindowListener( this ); }
6
7
public void windowClosing( WindowEvent event )
8
{ System.exit( 0 ); }
9
}
Search WWH ::
Custom Search