Win a copy of AWS Security this week in the Cloud/Virtualization forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
  • Campbell Ritchie
  • Paul Clapham
  • Jeanne Boyarsky
  • Junilu Lacar
  • Henry Wong
  • Ron McLeod
  • Devaka Cooray
  • Tim Cooke
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Frits Walraven
  • Tim Holloway
  • Carey Brown
  • Piet Souris
  • salvin francis
  • fred rosenberger

Applet Problem (getKeyCode( ) )

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()

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

int key = ke.getKeyCode();

case KeyEvent.VK_BACK_SPACE :
msg += " BACK SPACE ";

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

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

default :
msg += " UNDEFINED ";


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

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


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 ?
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:
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:
My previous laptop never exploded like that. Read this tiny ad while I sweep up the shards.
Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koop
    Bookmark Topic Watch Topic
  • New Topic