KeyEvents in Java


This applet demonstrates some virtual key codes using event handlers

import java.applet.*;
import java.awt.*;
import java.awt.event.*; /*

<applet code="KeyEvents" width = 300 height = 200></applet>

*/

public class KeyEvents 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_F1 :
msg += "<F1>";
break;

case KeyEvent.VK_F2 :
msg += "<F2>";
break;

case KeyEvent.VK_F3 :
msg += "<F3>";
break;

case KeyEvent.VK_PAGE_DOWN :
msg += "<PgDn>";
break;

case KeyEvent.VK_PAGE_UP :
msg += "<PgUp>";
break;

case KeyEvent.VK_LEFT :
msg += "<Left Arrow>";
break;

case KeyEvent.VK_RIGHT :
msg += "<Right Arrow>";
break;
}

repaint ();
}

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

public void keyTyped(KeyEvent ke) {
msg += ke.getKeyChar();
repaint();
}

public void paint(Graphics g) {
g.drawString(msg, X, Y);
}
}

Note : After you have studied the above code :

» Copy it onto your hard drive in Notepad or MS Word or any text editor. Save the file as "KeyEvents.java".
» Open a new text document, mention the applet parameters within the html parameters and save this file as "KeyEvents.html".
» Compile the .java file (from DOS prompt if you are not using a visual editor like VJ++, etc.) to check for errors and to obtain the .class file.
» Run at DOS prompt, using the command : appletviewer KeyEvents.java




Added on July 19, 2007 Comment
}