Posted By:
14 Feb, 2014 11:45 am PST

How to trap the key code and key name typed by the user on the keyboard

Write a program to trap the key code and key name typed by the user on the keyboard and display them in a text area.

//catching which key is pressed

import java.awt.*;

import java.awt.event.*;

public class Keys extends Frame implements KeyListener {

       //vars

       TextArea ta;

       String msg="";

       Keys()

       {

              //set Flow Layout

              setLayout(new FlowLayout());

              //create a text area to display the key code

              ta= new TextArea(5,25);

              //set some font and foreground color to text area

              Font f =new Font("SansSerif", Font.PLAIN,25);

              ta.setFont(f);

              ta.setBackground(Color.blue);

              ta.setForeground(Color.black);

              //add text area to frame

              add(ta);

              //add key listener to frame

              ta.addKeyListener(this);

              //closing the frame

              addWindowListener(new WindowAdapter()

              {

                     public void windowClosing(WindowEvent we)

                     {

                           System.exit(0);

                     }

                     });

              }// end of constructor

              public void keyPressed(KeyEvent ke)

       {

              //get the code of the key pressed

              int keycode=ke.getKeyCode();

              msg+="\nKey Code: "+keycode;

              //get the name of the key from the code

              String keyname=KeyEvent.getKeyText(keycode);

              msg+="\nKey Pressed: "+keyname;

              //display the key code and key name in text area

              ta.setText(msg);

              msg="";

       }

public void keyTyped(KeyEvent ke)

{}

public void keyReleased(KeyEvent ke){

       //get the key code released

       int keycode=ke.getKeyCode();

       msg+="\nKey Code: "+keycode;

       //get the key name from the code

       String keyname=KeyEvent.getKeyText(keycode);

       msg+="\nKey Released: "+keyname;

       //display the keycode and key name in text area

       ta.setText(msg);

}

public static void main(String [] args)

{

       //create the frame

       Keys k=new Keys();

       k.setSize(400,400);

       k.setTitle("CATCH THE KEYS");

       k.setVisible(true);

       }

       }

OUTPUT:

Attachment: workspace.zip


Video is posted for the better understanding of the concept.

Was it useful?  




Please login to reply to this problem.



Related Problems on Fixoncloud