Simple key press listener

With this simple tutorial we are going to see how to implement a simple key listener for your Java Desktop Application. This is a very nice tool if your application offers rich keyboard activity to the user.

In short, in order to implement a simple key listener in Java, one should perform these steps:

  • Create a new class that extends KeyAdapter class.
  • Override the keyPressed method to customize the handling of that specific event. Now every time the user presses a key this method will be launched.
  • Use KeyEvent.getKeyChar() and KeyEvent.getKeyCode() to find out which key the user pressed.

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

package com.javacodegeeks.snippets.desktop;

import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.JFrame;
import javax.swing.JTextField;

public class Main {

    public static void main(String[] argv) throws Exception {

  JTextField textField = new JTextField();

  textField.addKeyListener(new MKeyListener());

  JFrame jframe = new JFrame();


  jframe.setSize(400, 350);



class MKeyListener extends KeyAdapter {

    public void keyPressed(KeyEvent event) {

  char ch = event.getKeyChar();

  if (ch == 'a' ||ch == 'b'||ch == 'c' ) {



  if (event.getKeyCode() == KeyEvent.VK_HOME) {

System.out.println("Key codes: " + event.getKeyCode());


This was an example on how to implement a simple key listener in Java.

Byron Kiourtzoglou

Byron is a master software engineer working in the IT and Telecom domains. He is an applications developer in a wide variety of applications/services. He is currently acting as the team leader and technical architect for a proprietary service creation and integration platform for both the IT and Telecom industries in addition to a in-house big data real-time analytics solution. He is always fascinated by SOA, middleware services and mobile development. Byron is co-founder and Executive Editor at Java Code Geeks.
Notify of

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

Newest Most Voted
Inline Feedbacks
View all comments
5 years ago

Be sure to include
before the end of psvm, otherwise the JFrame will close, but not exit properly.

4 years ago

I tried to implement this into my code and ecplise threw this error before I tried running it: “No enclosing instance of type MouseClick is accessible. Must qualify the allocation with an enclosing instance of type MouseClick (e.g. x.new A() where x is an instance of MouseClick).”

What should I do?

Back to top button