我是applet编程的新手。我想要做的是当按键上按键时,它必须在小程序上显示。这是我的代码。
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);
}
}
但它没有在按键上显示任何内容。我的代码怎么了.. ??? 请帮我找出来!
答案 0 :(得分: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();
}
....
}