key event handlers in JAVA


An applet which demonstrates the key event handlers


import java.applet.*; import java.awt.*;

import java.awt.event.*;

/*

<applet code="SimpleKey" width = 300 height = 200>

</applet>

*/



public class SimpleKey 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");

}

public void keyReleased(KeyEvent ke) {

showStatus("Key Up");

}

public void keyTyped(KeyEvent ke) {

msg += ke.getKeyChar();

repaint();

}

public void paint(Graphics g) {

showStatus("Key Down");

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 "SimpleKey.java".

» Open a new text document, mention the applet parameters within the html parameters and save this file as   "SimpleKey.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 SimpleKey.java



Added on July 5, 2007 Comment
}