Adapter Classes
Adapter Classes
1
Java Event Listener
To receive notification of events of interest,
a program must install event listener
objects
It is not enough to simply know that an
event has occurred; we need to know the
event source
E.g., a key was pressed, but in which of
several text fields in the GUI was the key
pressed?
2
Listeners
3
Interfaces vs. Classes
4
Characteristics of Interfaces
Interfaces
Do not have instance variables
You cannot instantiate an object of an interface
Include only abstract methods
Methods have a signature (i.e., a name, parameters,
and return type)
Methods do not have an implementation (i.e., no
code)
Include only public methods and fields
Does not make sense to define private members if the
public members that could potentially use them are
themselves not implemented
5
Listeners (revisited)
8
Installing Listeners (3)
Signature for the addKeyListener method:
public void addKeyListener(KeyListener)
Description:
Adds the specified key listener to receive
key events from this component.
In our example, we used this as the specified
key listener
Indeed, the current instance of our extended
JFrame class (this) is a key listener because it
implements the key listener methods
Result: when a key pressed event occurs on the
enterArea component, the keyPressed method
in our extended JFrame class will execute! 9
Lets Say That Again
10
Event Sources
Javas event classes are all subclasses of
EventObject (see earlier slide)
EventObject includes the getSource method:
public Object getSource()
12
WindowAdapter
13
Using the WindowAdapter Class
14
Extending Adapters vs. Implementing Listeners
15
Pros and Cons
Using adapter classes
Advantage
Only the listener methods needed are defined
Disadvantage
A bit complicated to setup
Need to define an inner class, then instantiate an
object of the inner class to pass to the appropriate
add method
Implementing listener methods
Advantage
A class can implement many different listeners
Disadvantage
Must implement all the methods defined in the
listener (even those not used) 16
The Good, The Bad, and The Arcane
Do you like creating code that mere mortals find
incomprehensible? If so, youll like this one.
Delete the inner class definition
private class WindowCloser extends WindowAdapter
{ public void windowClosing(WindowEvent we)
{ System.exit(0);
}
}
and replace this
this.addWindowListener(new WindowCloser());
with this
this.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e)
{ System.exit(0);}
}); 17