0

我是小程序编程的新手。我想要做的是,当键盘上的某个键被按下时,它必须在小程序上显示它。这是我的代码。

public class sample extends Applet implements KeyListener {
private Graphics graphic;
@Override
public void init(){
    addKeyListener(this);
}
@Override
public void paint(Graphics g){
    graphic=g;
    g.drawString("hello",20,30);
}

public void keyTyped(KeyEvent e) {
    char key=e.getKeyChar();
    dis(key,graphic);
}

public void keyPressed(KeyEvent e) {

}

public void keyReleased(KeyEvent e) {

}

private void dis(char key, Graphics graphic) {
    graphic.drawString(" "+key,50,60);
  }
} 

但它没有在按键上显示任何内容。我的代码有什么问题..??? 请帮我找出来!

4

1 回答 1

3

不要保存Graphics对象。尝试repaint()从处理程序中调用该方法。

public class sample extends Applet implements KeyListener {
String msg="";
@Override
public void init(){
    addKeyListener(this);
}
@Override
public void paint(Graphics g){
    g.drawString(msg,20,30);
}

public void keyTyped(KeyEvent e) {
    char key=e.getKeyChar();
    msg="KeyTyped : " + key;
    repaint();
 }
 ....
}
于 2012-06-13T05:22:53.967 回答