Friday, 19 December 2014

KeyListener in Java

//save as KeyListenerDemo.java 
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class KeyListenerDemo extends Applet implements KeyListener
{
    String s = "";

    public void init()
    {
        addKeyListener(this);
        requestFocus();     //request input focus.
    }
  
    //Handle when a key has been pressed...
    public void keyPressed(KeyEvent ke)
    {
        showStatus("Key Pressed...");
        repaint();
    }

    //Handle when a key has been released...
    public void keyReleased(KeyEvent ke)
    {
        showStatus("Key Released...");
        repaint();
    }
  
    //Handle when a key has been pressed...
    public void keyTyped(KeyEvent ke)
    {
        s += ke.getKeyChar();
        repaint();
    }
  
    //display keystrokes.
    public void paint(Graphics g)
    {
        g.drawString(s,x,y);
    }
}

/*


*/
Output

No comments:

Post a Comment