A complete KeyListener Java Example

In this article,we will talk about java key listener and we will demonstrate a complete KeyListener Java example.

1. Introduction

Java key listener is an interface used in Java Swing to monitor keyboard-related events that take place in your applications. This is particularly useful when you want to perform input validation on form fields or add shortcut functionality to your application.

KeyListener Java

2. KeyListener Java API

The java keyboard listener interface extends the EventListener interface and has the following method signatures:

  • void keyPressed(KeyEvent e) This method is invoked when a key has been pressed.
  • void keyReleased(KeyEvent e)This method is invoked when a key has been released.
  • void keyTyped(KeyEvent e)This method is invoked when a key has been typed.

3. A Simple KeyListener Java Class

In this section, we will see the implementation of KeyListenerExample.java. The steps to implement the class are as follows:

  • Create a new KeyListener object.
  • Override the methods that correspond to the key events you want to monitor e.g keyPressed, keyReleased, keyTyped.
  • Create a JTextField component
  • Use it’s addKeyListener method to add to it the KeyListener you’ve created.

Let’s take a closer look at the code snippet that follows:

package com.javacodegeeks.snipppets.desktop;

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import javax.swing.JFrame;
import javax.swing.JTextField;

public class KeyListenerExample {

    public static void main(String args[]) {
        JFrame frame = new JFrame("Key Listener");
        Container contentPane = frame.getContentPane();
        KeyListener listener = new KeyListener() {
            public void keyPressed(KeyEvent event) {
                printEventInfo("Key Pressed", event);
            public void keyReleased(KeyEvent event) {
                printEventInfo("Key Released", event);
            public void keyTyped(KeyEvent event) {
                printEventInfo("Key Typed", event);
            private void printEventInfo(String str, KeyEvent e) {
                int code = e.getKeyCode();
                System.out.println("   Code: " + KeyEvent.getKeyText(code));
                System.out.println("   Char: " + e.getKeyChar());
                int mods = e.getModifiersEx();
                System.out.println("    Mods: "
                        + KeyEvent.getModifiersExText(mods));
                System.out.println("    Location: "
                        + keyboardLocation(e.getKeyLocation()));
                System.out.println("    Action? " + e.isActionKey());
            private String keyboardLocation(int keybrd) {
                switch (keybrd) {
                    case KeyEvent.KEY_LOCATION_RIGHT:
                        return "Right";
                    case KeyEvent.KEY_LOCATION_LEFT:
                        return "Left";
                    case KeyEvent.KEY_LOCATION_NUMPAD:
                        return "NumPad";
                    case KeyEvent.KEY_LOCATION_STANDARD:
                        return "Standard";
                    case KeyEvent.KEY_LOCATION_UNKNOWN:
                        return "Unknown";
        JTextField textField = new JTextField();
        contentPane.add(textField, BorderLayout.NORTH);

4. KeyListenerLoginFormExample

In this section, we will see an example implementation where the KeyListener class is used to perform validation on a user name input field.

package com.javacodegeeks.snipppets.desktop;

import javax.swing.*;
import javax.swing.border.Border;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

public class KeyListenerLoginFormExample {
    public static void main(String args[]) {
        JPanel inputPanel = new JPanel();
        JFrame frame = new JFrame("Login Form");
        Container pane = frame.getContentPane();
        JLabel userNameInvalidLabel = new JLabel();
        JLabel userNameLabel = new JLabel("User Name");
        JTextField userNameTextField = new JTextField( 15);
        KeyListener listener = new KeyListener() {
            public void keyPressed(KeyEvent event) {

            public void keyReleased(KeyEvent event) {


            public void keyTyped(KeyEvent event) {
            private void validateUserName(KeyEvent event) {
                int num = event.getKeyChar();
                if(!Character.isDigit(event.getKeyChar())) {
                if(event.getKeyChar()==KeyEvent.VK_ENTER) {
                    userNameInvalidLabel.setText("Your username is valid!!");
                else {
        pane.add(inputPanel, BorderLayout.PAGE_START);


In the above class, we see the usage of the keyTyped and keyPressed methods in the KeyListener implementation. The event.consume() statement in lines 35 and 40, will reset the value typed into the text field. Thus, through the validateUserName() method, we are able to make sure that userNameTextField only accepts numbers.

5. Summary

In this article, we were able to show 2 different usages and implementation of KeyListener in Java.

6. Download the Source Code

This was a complete KeyListener Java Example.

You can download the full source code of this example here: A Complete KeyListener Java Example

Last updated on Jun. 11th, 2020

Want to know how to develop your skillset to become a Java Rockstar?

Join our newsletter to start rocking!

To get you started we give you our best selling eBooks for FREE!


1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design


and many more ....


Receive Java & Developer job alerts in your Area

I have read and agree to the terms & conditions


Sowmya Shankar

Sowmya works as a Senior Web Applications Programmer in the higher educational sector, where she leads projects based on Java. She graduated from Anna University's Computer Sciences department, followed by a Masters degree in Computer and Information Sciences from the University of Delaware. Her project portfolio features diverse web applications using frameworks such as Struts2, Spring, Spring Boot, as well as her recent experiments in the world of Microservices and the React JS framework.
Notify of

This site uses Akismet to reduce spam. Learn how your comment data is processed.

1 Comment
Newest Most Voted
Inline Feedbacks
View all comments
2 years ago

Awesome! thanks

Back to top button