1: import Java.awt.Graphics;
2: import Java.awt.Event;
3: import Java.awt.Font;
4:
5: public class Keys extends Java.applet.Applet {
6:
7: char currkey;
8: int currx;
9: int curry;
10:
11: public void init() {
12: currx = (this.size().width / 2) -8; // default
13: curry = (this.size().height / 2) -16;
14:
15: setBackground(Color.white);
16: setFont(new Font(“Helvetica”,Font.BOLD,36));
17: }
18:
19: public boolean keyDown(Event evt, int key) {
20: switch (key) {
21: case Event.DOWN:
22: curry += 5;
23: break;
24: case Event.UP:
25: curry -= 5;
26: break;
27: case Event.LEFT:
28: currx -= 5;
29: break;
30: case Event.RIGHT:
31: currx += 5;
32: break;
33: default:
34: currkey = (char)key;
35: }
36:
37: repaint();
38: return true;
39: }
40:
41: public void paint(Graphics g) {
42: if (currkey != 0) {
43: g.drawString(String.valueOf(currkey), currx,curry);
44: }
45: }
46: }
另:
Java Tutorial: Run KeyEventDemo
http://Java.sun.com/docs/books/tutorial/uiswing/events/KeyEventDemo.Html
source code
http://java.sun.com/docs/books/tutorial/uiswing/events/example-swing/KeyEventDemo.Java
:)