Java Reference
In-Depth Information
The
WindowAdapter
Class
In Display 18.2 we gave empty bodies to most of the method headings in the
WindowListener
interface. The abstract class
WindowAdapter
is a way to avoid all those
empty method bodies. The class
WindowAdapter
does little more than provide trivial
implementations of the method headings in the
WindowListener
interface. So, if you
make a window listener a derived class of the class
WindowAdapter
, then you only need
to define the method headings in the
WindowListener
interface that you need. The
other method headings inherit trivial implementations from
WindowAdapter
.
(
WindowAdapter
is unusual in that it is an abstract class with no abstract methods.)
For example, in Display 18.3 we have rewritten the inner class
CheckOnExit
from
Display 18.2, but this time we made it a derived class of the
WindowAdapter
class. This
definition of
CheckOnExit
is much shorter and cleaner than the one in Display 18.2,
but the two implementations of
CheckOnExit
are equivalent. Thus, you can replace the
definition of
CheckOnExit
in Display 18.2 with the shorter one in Display 18.3. The
file
WindowListenerDemo2
on the accompanying CD contains a version of Display
18.2 with this shorter definition of
CheckOnExit
.
The class
WindowAdapter
is in the
java.awt.event
package and so requires an
import
statement such as the following:
extra code
on CD
import
java.awt.event.WindowAdapter;
You cannot always define your window listeners as derived classes of
Windowdapter
.
For example, suppose you want a
JFrame
class to be its own window listener. To
accomplish that, the class must be a derived class of
JFrame
and so cannot be a derived
class of any other class such as
WindowAdapter
. In such cases, you make the class a
derived class of
JFrame
and have it implement the
WindowListener
interface. See Self-
Test Exercise 4 for an example.
Display 18.3
Using
WindowAdapter
This requires the following import statements:
import
java.awt.event.WindowAdapter;
import
java.awt.event.WindowEvent;
1
private class
CheckOnExit
extends
WindowAdapter
2
{
3
public void
windowClosing(WindowEvent e)
4
{
5
ConfirmWindow checkers =
new
ConfirmWindow();
6
checkers.setVisible(
true
);
7
}
8
}
//End of inner class CheckOnExit
If the definition of the inner class
CheckOnExit
in Display 18.2 were replaced with
this definition of
CheckOnExit
, there would be no difference in how the outer class
or any class behaves.