Java Reference
In-Depth Information
This leaves only the notification of the listeners to be handled. No generic method exists in
the class to notify all the listeners of a particular type that an event has happened, so you must
create the code yourself. A call to the following code ( fireActionPerformed(actionEvent) ) will
replace the one line of boldfaced source code:
(actionListenerList.actionPerformed(actionEvent)
from the previous example. The code gets a copy of all the listeners of a particular type from the
list as an array (in a thread-safe manner). You then need to loop through the list and notify the
appropriate listeners.
protected void fireActionPerformed(ActionEvent actionEvent) {
EventListener listenerList[] =
actionListenerList.getListeners(ActionListener.class);
for (int i=0, n=listenerList.length; i<n; i++) {
((ActionListener)listenerList[i]).actionPerformed(actionEvent);
}
}
The complete source for the new and improved class follows in Listing 2-6. When using the
EventListenerList class, don't forget that the class is in the javax.swing.event package. Other
than the component class name, the testing program doesn't change.
Listing 2-6. Managing Listener Lists with EventListenerList
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import java.util.EventListener;
public class KeyTextComponent2 extends JComponent {
private EventListenerList actionListenerList = new EventListenerList();
public KeyTextComponent2() {
setBackground(Color.CYAN);
KeyListener internalKeyListener = new KeyAdapter() {
public void keyPressed(KeyEvent keyEvent) {
if (actionListenerList != null) {
int keyCode = keyEvent.getKeyCode();
String keyText = KeyEvent.getKeyText(keyCode);
ActionEvent actionEvent = new ActionEvent(
this,
ActionEvent.ACTION_PERFORMED,
keyText);
fireActionPerformed(actionEvent);
}
}
};
Search WWH ::




Custom Search