Java Reference
In-Depth Information
interfaces or anonymous definitions. If not, this approach causes confusion ('But,
then where is my listener after all?').
In the three modifications of CounterPanel presented in this section, one
can also avoid defining the methods increment and decrement . Instead one can
transfer the respective code to the appropriate places in the listener.
9.2.5
Listeners and adapters
Listeners require the implementation of all their methods. Often one is interested
in only one of them and the rest are implemented with empty bodies. To save
some work, Java supplies classes that implement all the listener interface methods
with empty bodies. The name for such a class is the name of the corresponding
listener interface with 'Listener' replaced by 'Adapter', e.g. the class implementing
a MouseListener is called a MouseAdapter .
Adapters are present for most listeners that require more than one method to be
implemented. Then, instead of implementing all methods of the listener interface
one only has to override the desired method of the corresponding adapter class .
9.3
Other kinds of listener
There are other kinds of listeners that are of interest, for example KeyListener ,
DocumentListener and WindowListener . Key listeners react to key strokes. A
document listener monitors changes in text documents; see Chapter 18. Window
listeners react to events related to 'windows', i.e. 'frames' in Java. Such events are
for example opening a window, closing it, turning it into an icon or activating it.
We focus on closing the window here, i.e. on the event that occurs when the 'close'
button of a frame is pressed.
In our basic frame class SimpleFrame we used the command
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
to immediately exit the application when the 'close' button is pressed. Often one
would like to perform some clean-up or rescue work before termination, such as
saving changed data to the disk. We define class CleanUpFrame which defines a
method cleanUp to perform this work. In our example it just writes a message to
the console and then exits the application. CleanUpFrame uses a window listener
to activate this method.
As we use only one of the seven methods of interface WindowListener we
actually use the corresponding adapter class WindowAdapter and thus avoid im-
plementing six methods. We implement the class as an internal class Clean-
UpAdapter .Itimplements method windowClosing(WindowEvent we) which is
automatically called by the runtime system when the 'close' button is pressed.
Method windowClosing then calls the cleanUp method of the frame. In the con-
structor of CleanUpFrame an instance of CleanUpAdapter is created and assigned
to the frame.
Search WWH ::




Custom Search