//TestKeyListener.java
import java.applet.Applet;
import java.awt.Graphics;
import java.awt.Color;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
public class TestKeyListener extends Applet implements KeyListener
{
Color clr;
public void init()
{
addKeyListener(this);
}
public void keyTyped(KeyEvent e)
{
if(e.getKeyChar()=='r'||e.getKeyChar()=='R')
clr=Color.red;
else if(e.getKeyChar()=='g'||e.getKeyChar()=='G')
clr=Color.green;
else if(e.getKeyChar()=='b'||e.getKeyChar()=='B')
clr=Color.blue;
else
clr=Color.black;
setBackground(clr);
}
public void keyReleased(KeyEvent e){}
public void keyPressed(KeyEvent e){}
}
//编译得到TestKeyListener.class文件
//KeyListener.html
<HTML>
<BODY>
<APPLET CODE="TestKeyListener.class" HEIGHT=300 WIDTH=300>
</APPLET>
</BODY>
</HTML>
//TestKeyListener.class和KeyListener.html在同一目录下
运行后程序对键盘的敲击没反应,不知道是怎么回事?
------解决方案--------------------
运行后在白色区域点一下就行了
刚开始的时候事件源没得到焦点