Win a copy of The Little Book of Impediments (e-book only) this week in the Agile and Other Processes forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Applet Problem (getKeyCode( ) )

 
jquest
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
// Demonstrate the key event handlers
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class KeyTest extends Applet
implements KeyListener
{
String msg = " ";
int x = 10, y = 20;

public void init()
{
addKeyListener(this);
requestFocus();
}

public void keyPressed(KeyEvent ke)
{
showStatus("Key Down");

int key = ke.getKeyCode();

switch(key)
{
case KeyEvent.VK_BACK_SPACE :
msg += " BACK SPACE ";
break;

case KeyEvent.VK_ENTER :
msg += " ENTER ";
break;

case KeyEvent.VK_SPACE :
msg += " SPACE BAR ";
break;

default :
msg += " UNDEFINED ";

}
repaint();
}

public void keyReleased(KeyEvent ke)
{
showStatus("Key Up");
}

public void keyTyped(KeyEvent ke)
{
if(ke.getKeyCode() != KeyEvent.VK_ENTER)//PROBLEM BLOCK
{
msg += ke.getKeyChar();
repaint();
}

}

public void paint(Graphics g)
{
g.drawString(msg, x, y);

}
}

In the above code see the //PROBLEM BLOCK
In this code when ever the "Enter" key is pressed the word "ENTER" is
added to the string msg . But the problem is that along with the word
"ENTER" an unknown character is also added to the string msg.
Q1. I think that the if condition block is not getting executed properly Why this is happening , please explain ?
Please run the above code on your machine .
According to this condition when ever the "Enter" key is pressed
the statements in if block should not execute and nothing should be added to the string msg .
Q2. But if I use (ke.getKeyChar() != KeyEvent.VK_ENTER) instead of
(ke.getKeyCode() != KeyEvent.VK_ENTER) every thing works fine.
Why it's NOT working with ke.getKeyCode() please explain ?
 
Stephanie Grasson
Ranch Hand
Posts: 347
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
KeyEvent method getKeyCode always returns 0. This is why the if statement is not working. See the link below for more information:
http://developer.java.sun.com/developer/bugParade/bugs/4034970.html
Hope this is helpful.
Also, please be sure to register with a proper ID. "jquest" does not count. We value your posts and would hate to see your account be disabled for this reason. See the following link for more information:
http://www.javaranch.com/name.html
Thanks.
Stephanie
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic