by Dinesh Thakur

The java.awt.event.KeyListener interface, present in virtually all AWT component is used to respond to events triggered by  keystrokes when the focus is on the component. Allows the preprocessing  the input provided by the user and other sophisticated actions. its  interface requires the keyPressed, keyReleased method are implemented and  keyTyped. The associated event, java.awt.event.KeyEvent has the following methods  of particular interest are listed below:

 

Method

Description

getKeyChar()

Returns the characterassociated with thekeythat originated theevent.

getKeyCode()

Returns thekey codeassociated withthatkeyoriginated the event.

getKeyModifiersText(int)

Returnsa string describingthe modifier keys"Shift", "Ctrl" ortheir combination.

getKeyText(int)

Returnsa string describingthe keyas"Home", "F1" or "A".

isActionKey()

Determines whetheror notthe associated keyis akeyaction.

setKeyChar(char)

Replaces the characterassociated with thekeythat originated theevent.

 

import javax.swing.*;

import java.awt.*;
import java.awt.event.*;
public class JavaExampleKeyEvent extends JFrame implements KeyListener
  {
    private JLabel LblPrmpt = new JLabel("Press keys as Desired Below:");
    private JLabel LblOutPt = new JLabel("Key Typed is:");
    private JTextField Txt = new JTextField(10);
    public JavaExampleKeyEvent()
     {
       setTitle("Java Example of Key Event");
       setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
       setLayout(new BorderLayout());
       add(LblPrmpt,BorderLayout.NORTH);
       add(Txt, BorderLayout.CENTER);
       add(LblOutPt,BorderLayout.SOUTH);
       addKeyListener(this);
       Txt.addKeyListener(this);
     }
       public void keyTyped(KeyEvent Evnt)
        {
          char s = Evnt.getKeyChar();
          LblOutPt.setText("Last key Pressed:" + s);
        }
          public void keyPressed(KeyEvent Evnt)
           {
           }
             public void keyReleased(KeyEvent Evnt)
             {
             }
               public static void main(String[] ar)
                {
                  JavaExampleKeyEvent Frm = new JavaExampleKeyEvent();
                  final int WIDTH = 250;
                  final int HEIGHT = 100;
                  Frm.setSize(300,300);
                  Frm.setVisible(true);
                }
  }

KeyEvent