KeyListener in Java


This article explains implementation of a Key Listener in Java. The Netbeans IDE is used for the development of the example.

What is Key Listener

The basic purpose of the Key Listener interface is for when an operation is performed on the keyboard, when a key is pressed or released the Key Listener interface is invoked.

Methods of Key Listener

  • KeyTyped(KeyEvent)

         This method is invoked just after the user types a Unicode character.

  • KeyPressed(KeyEvent)

          This method is called just after the user presses the key.

  • KeyReleased(KeyEvent)

         This method is called just after the user releases the key.

Packages Imported


AWT stands for Abstract Window Toolkit. The AWT package is imported to use the AWT components like label, text and so on.


This package is imported to handle the action events caused by the components.


Swing is an extended version of AWT, and it is used to provide a Graphical User Interface to programs. This package is imported to use swing components like Jlabel, JTextArea so on.

Advantages of Key Listener

  • It is easy to use.
  • The source code is very short.


In this example; we implement a Key Listener in Java using the Netbeans IDE. There are certain steps in the Netbeans IDE that we need to follow as explained below.

Step 1

Open the Netbeans IDE.


Step 2

Click on "File" from the Menu bar as in the following:


Step 3

Click on "New Project" as in the following:


Step 4

Select "Java" and "Java application" then click on "Next" as in the following:


Step 5

Instead of the project name specify "KeyEventDemo" and instead of main class also specify "KeyEventDemo" and click on "Finish".


Step 6

In this class write the following code (the class name is "KeyEventDemo"):

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

public class KeyEventDemo


  JTextArea ta;

  JTextArea fd;

  public static void main(String[] args)


   EventQueue.invokeLater(new Runnable()



    public void run()


     new KeyEventDemo();        




   public KeyEventDemo()


    JFrame f = new JFrame();


    f.setTitle("Creating a Table Example");



    fd = new JTextArea();

    JScrollPane sp = new JScrollPane(fd);

    ta = new JTextArea();

    ta.addKeyListener(new KeyListener()



     public void keyPressed(KeyEvent e)


     fd.append("Key Pressed: " + e.getKeyChar() + "\n");



     public void keyReleased(KeyEvent e)


     fd.append("Key Released: " + e.getKeyChar() + "\n");



     public void keyTyped(KeyEvent e)


     fd.append("Key Typed: " + e.getKeyChar() + " " + KeyEvent.getKeyModifiersText(e.getModifiers()) + "\n");



     f.add(ta, BorderLayout.NORTH);

     f.add(sp, BorderLayout.CENTER);








Step 7

Now go to "" and right-click on that, click on "Run" from the menu bar as in the following:



 The output shows that when we press and release a key on the keyboard, it gives notification.