event

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.add(textField);

  jframe.setSize(400, 350);

  jframe.setVisible(true);

    }
}

class MKeyListener extends KeyAdapter {

    @Override
    public void keyPressed(KeyEvent event) {

  char ch = event.getKeyChar();

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

System.out.println(event.getKeyChar());

  }

  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.
Subscribe
Notify of
guest

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

2 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Koios
Koios
6 years ago

Be sure to include
jframe.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
before the end of psvm, otherwise the JFrame will close, but not exit properly.

Warren
Warren
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