Java Reference
In-Depth Information
and annoyances that come along with it. In particular, we find that the listener
interfaces hold up to six methods that must be implemented. (Remember that all
methods in an interface are abstract and so concrete implementations for each
must be provided.) If you need only one or a few of these methods, you must
nevertheless implement all of the remaining methods with empty code bodies.
In the
AnonListenterApplet
example given here, we use an anony-
mous
MouseListener
class but only one of the five methods declared in the
MouseListener
interface is actually needed:
...Inthe
AnonListenerApplet
class
...
void init ()
{
Container content
-
pane
=
getContentPane ();
// Create an instance of JPanel
JPanel panel
=
new JPanel ();
// User an anonymous MouseListener object with the
// panel
panel.addMouseListener (
new MouseListener () {
public void mouseEntered (MouseEvent e) {
System.out.println (e.toString ());
}
// Give empty code bodies to these unneeded
// methods.
public void mouseClicked (MouseEvent e) {}
public void mousePressed (MouseEvent e) {}
public void mouseReleased (MouseEvent e) {}
public void mouseExited (MouseEvent e) {}
}
);
// Add the panel to the content pane.
content
-
pane.add (panel);
}
// init
. ..rest of code in
AnonListenerApplet . . .
To avoid writing empty versions of all those unneeded methods, the
java.awt.event
package provides adapter classes for seven of the listener
interfaces. These adapters have implemented the interface methods with empty
methods. Since the adapters are concrete (non-abstract) classes, we only need to
override the methods of interest.
Search WWH ::
Custom Search