Java Reference
In-Depth Information
LISTING 12.5
The Full Text of KeyChecker.java
1: import java.awt.*;
2: import java.awt.event.*;
3: import javax.swing.*;
4:
5: public class KeyChecker extends JFrame {
6: JLabel keyLabel = new JLabel(“Hit any key”);
7:
8: public KeyChecker() {
9: super(“Hit a Key”);
10: setSize(300, 200);
11: setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
12: setLayout(new FlowLayout(FlowLayout.CENTER));
13: KeyMonitor monitor = new KeyMonitor(this);
14: setFocusable(true);
15: addKeyListener(monitor);
16: add(keyLabel);
17: setVisible(true);
18: }
19:
20: public static void main(String[] arguments) {
21: new KeyChecker();
22: }
23: }
24:
25: class KeyMonitor extends KeyAdapter {
26: KeyChecker display;
27:
28: KeyMonitor(KeyChecker display) {
29: this.display = display;
30: }
31:
32: public void keyTyped(KeyEvent event) {
33: display.keyLabel.setText(“” + event.getKeyChar());
34: display.repaint();
35: }
36: }
12
Summary
The event-handling system used with Swing is added to a program through the same
steps:
A listener interface is added to the class that will contain the event-handling
methods.
n
 
 
Search WWH ::




Custom Search