RAVITEJA SATYAVADA
RAVITEJA SATYAVADA

Reputation: 2571

Issue with applet code

I new to applet programming. What iam trying to do is when ever a key pressed on key board, it has to display that on the applet. Here is my code.

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);
  }
} 

But it is not displaying anything on key press. Whats wrong with my code..??? Please help me to find out it!

Upvotes: 0

Views: 58

Answers (1)

KV Prajapati
KV Prajapati

Reputation: 94625

Do not save the Graphics object. Try to call the repaint() method from within the handlers.

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();
 }
 ....
}

Upvotes: 3

Related Questions