How to listen to and take action on keyboard strokes in Java

Introduction

To detect keystrokes and perform actions in a Java application, we need two classes, KeyAdapter and KeyEvent.

The KeyAdapter and KeyEvent classes

The KeyAdapter class is an abstract class that implements the KeyListener interface; it belongs to the package java.awt.event.

The KeyAdapter class has 3 overridable methods: keyPressed, keyReleased, and keyTyped.

Methods of KeyAdapter class

1. keyPressed method

Syntax:

void keyPressed(KeyEvent e)

Description:
The keyPressed function is invoked when a key has been pressedheld down on the keyboard. The argument e contains the information of the pressed key.

2. keyReleased method

Syntax:

void keyReleased(KeyEvent e)

Description:
The keyReleased function is invoked when a key has been released on the keyboard. The argument e contains the information of the released key.

3. keyTyped method

Syntax:

void keyTyped(KeyEvent e)

Description:
The keyTyped function is invoked when a key has been pressed and then released on the keyboard. The argument e contains the information of this key.

The KeyEvent argument

All three of the above methods have only one parameter, e of type KeyEvent.

The KeyEvent argument contains the details of which key is pressed. These details can be fetched by invoking the built-in methods defined in the KeyEvent class. The method relevant for our use case is the getKeyCode method, which returns the integer key code value through which the key can be identified.

A keystroke detection application

Let’s say that we want to build an application that detects and prints the pressed arrow key on the standard output. We will start with a boilerplate code for a JFrame application, as follows:

import javax.swing.JFrame;

public class Main {
  public static void main(String[] argv) throws Exception {
    JFrame myJFrame = new JFrame();

    myJFrame.setVisible(true);
  }
}

First, we’ll add the following two import statements at the top:

import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

Next, we’ll use the addKeyListener method that is implemented by the JFrame class inside the main function. The addKeyListener function takes an instance of a class that implements KeyListener interface; in our case, this is the KeyAdapter class:

myJFrame.addKeyListener(new KeyAdapter() {

});

Now, inside this new KeyAdapter instance, we’ll override the keyPressed method. This method will check whether the pressed key is one of the arrow keys; if so, an appropriate message will be displayed on the standard output. The code is as follows:

myJFrame.addKeyListener(new KeyAdapter() {
  public void keyPressed(KeyEvent e) {
    int keyCode = e.getKeyCode();
    if (keyCode == KeyEvent.VK_UP) {
      System.out.println("Up Arrrow-Key is pressed!");
    }
    else if (keyCode == KeyEvent.VK_DOWN) {
      System.out.println("Down Arrrow-Key is pressed!");
    }
    else if (keyCode == KeyEvent.VK_LEFT) {
      System.out.println("Left Arrrow-Key is pressed!");
    }
    else if (keyCode == KeyEvent.VK_RIGHT) {
     System.out.println("Right Arrrow-Key is pressed!");
    }
  }
});

In the above code, the variable keyCode stores the integer value for the pressed key by invoking the getKeyCode method on e. The following if statements check whether the key is one of the arrow keys; if so, a message is printed onto the standard output specifying which arrow key is pressed.

Note: The KeyEvent.VK_ text represents a static int part of the KeyEvent class. The variables VK_UP, VK_DOWN, VK_LEFT, and VK_RIGHT represent the up, down, left, and right arrow key values respectively.

The following code snippet contains the complete code. You can copy and run it in your preferred IDE:

import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.JFrame;
public class Main {
public static void main(String[] argv) throws Exception {
JFrame myJFrame = new JFrame();
myJFrame.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
int keyCode = e.getKeyCode();
if (keyCode == KeyEvent.VK_UP) {
System.out.println("Up Arrrow-Key is pressed!");
}
else if (keyCode == KeyEvent.VK_DOWN) {
System.out.println("Down Arrrow-Key is pressed!");
}
else if (keyCode == KeyEvent.VK_LEFT) {
System.out.println("Left Arrrow-Key is pressed!");
}
else if (keyCode == KeyEvent.VK_RIGHT) {
System.out.println("Right Arrrow-Key is pressed!");
}
}
});
myJFrame.setVisible(true);
}
}
Copyright ©2024 Educative, Inc. All rights reserved