Java Reference
In-Depth Information
If you use the inner class mechanism to handle a window event, you can create the class
by extending the definition of the
class
WindowAdapter
and provide the definition of
only the methods that the program needs. Similarly, to handle window events, if the class
containing the application program does not extend the definition of another class, you
can make that class extend the definition of the
class
WindowAdapter
.
Chapter 6 discussed in detail how to use the inner class mechanism. The GUI part of the
programming example in Chapter 10, which can be found in the Additional Student Files
folder at www.cengagebrain.com, explained how to make the class containing the application
program implement more than one interface. As stated in Chapter 10, there is one more
way to handle events in a program—using the mechanism of anonymous classes. This
mechanism is quite useful to handle events such as window and mouse events because the
corresponding interfaces contain more than one method, and the program might want to
use only one method.
Recall from Chapter 6 that to register an action listener object to a GUI component, you
use the method
addActionListener
. To register a
WindowListener
object to a GUI
component, you use the method
addWindowListener
. The
WindowListener
object
being registered is passed as a parameter to the method
addWindowListener
.
Consider the following code:
this
.addWindowListener(
new
WindowAdapter()
{
public void
windowClosing(WindowEvent e)
{
System.exit(0);
}
}
);
The preceding statements create an object of the anonymous class, which extends the
class
WindowAdapter
and overrides the method
windowClosing
. The object created
is passed as an argument to the method
addWindowListener
. The method
addWindowListener
is invoked by explicitly using the reference
this
.
Similarly, you can handle mouse events by using the
interface
MouseListener
. The
definition of the
interface
MouseListener
and the
class
MouseAdapter
is:
public interface
MouseListener
{
1
1
void
mouseClicked(MouseEvent e);
//This method executes when a mouse button is clicked
//on a component.
void
mouseEntered(MouseEvent e);
//This method executes when the mouse enters a component.
void
mouseExited(MouseEvent e);
//This method executes when the mouse exits a component.
void
mousePressed(MouseEvent e);
//This method executes when a mouse button is
//is pressed on a component.
Search WWH ::
Custom Search