Java Reference
In-Depth Information
The remainder of the class definition describes how to handle the internal events. An
internal KeyListener needs to be registered in order to send keystrokes to an ActionListener .
In addition, the component must be able to get the input focus; otherwise, all keystrokes will
go to other components. The complete class definition is shown in Listing 2-4. The line of
source code for notification of the listener list is in boldface. That one line notifies all the regis-
tered listeners.
Listing 2-4. Managing Listener Lists with AWTEventMulticaster
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class KeyTextComponent extends JComponent {
private ActionListener actionListenerList = null;
public KeyTextComponent() {
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);
actionListenerList.actionPerformed(actionEvent);
}
}
};
MouseListener internalMouseListener = new MouseAdapter() {
public void mousePressed(MouseEvent mouseEvent) {
requestFocusInWindow();
}
};
addKeyListener(internalKeyListener);
addMouseListener(internalMouseListener);
}
public void addActionListener(ActionListener actionListener) {
actionListenerList = AWTEventMulticaster.add(
actionListenerList, actionListener);
}
Search WWH ::




Custom Search