Listeners
are created by using one or more of the interfaces defined by the java.awt.event package.
Example:
import
java.awt.event.*;
import
java.applet.*;
import
java.awt.*;
public
class MyKeyApplet extends Applet implements KeyListener
{
String msg="";
int x=10,y=40;
public void init()
{
addKeyListener(this);
}
public void paint(Graphics g)
{
g.drawString(msg,x,y);
}
public void keyPressed(KeyEvent e)
{
int keycode=e.getKeyCode();
switch(keycode)
{
case KeyEvent.VK_PAGE_UP:msg+=" Page UP
";
break;
case KeyEvent.VK_LEFT:msg+=" Left Arrow
";
break;
}
repaint();
}
public void keyTyped(KeyEvent e)
{
msg+=e.getKeyChar();
repaint();
}
public void keyReleased(KeyEvent e)
{
msg+="Key Released";
repaint();
}
}
OUTPUT:
In the above example,
whenever a keyboard button is pressed, appropriate message is displayed on the
applet screen. With the help of appropriate listener the various event
generated through keyboard can be handled.
No comments:
Write comments