How to Use KeyListener in Java

Mohammad Irfan Feb 02, 2024
  1. KeyEvent Class
  2. Implementing the KeyListener Interface
  3. A Simple Application of KeyListener
  4. A Simple Game Application using KeyListener
  5. Summary
How to Use KeyListener in Java

This tutorial introduces how to use KeyListener in Java and lists some example codes to understand the topic.

KeyListener is an interface that deals with changes in the state of the keys of our keyboard. As the name of the interface suggests, it listens to the keys and acts accordingly.

In this tutorial, we will learn how to implement this interface and work with key events.

KeyEvent Class

Whenever a keyboard key is pressed, an object of the KeyEvent class notifies the KeyListener. The KeyEvent class has a few methods used to get more information about the key event. Three of the most important methods of this class are summarized below.

  • The getKeyChar() method fetches the key character associated with the event. This method is very beneficial if we want to add some functionality to a particular key. For example, if e is pressed, then the application should exit.
  • The getKeyCode() method is very similar to the getKeyChar() method. It returns an integer key-code associated with the pressed key.
  • The isActionKey() method can tell whether an action key(like Caps Lock) is pressed. It returns a Boolean true or false.

Implementing the KeyListener Interface

The KeyListener interface listens to key events and performs some action. The declaration of this interface is shown below.

public interface KeyListener extends EventListener

We need to override the following three methods of this interface in our class.

  • The keyPressed(KeyEvent e) method will be invoked when a key is pressed.
  • The keyReleased(KeyEvent e) method will be invoked when the key is released.
  • The keyTyped(KeyEvent e) method will be invoked when a key types a character.

We will also use the addKeyListener() method. We need to pass an object of the class that implements the KeyListener interface to this method. It is a way of registering the object to listen and react to key events.

A Simple Application of KeyListener

Let’s create a simple application that listens to key events and prints something to the console. We will create a frame and add a label to it. Our program should print the key character and the key action to the console. If the key pressed is an action key, then the program should terminate.

import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.Label;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
public class KeyListenerExample implements KeyListener {
  @Override
  public void keyTyped(KeyEvent e) {
    System.out.println("The key Typed was: " + e.getKeyChar());
  }
  @Override
  public void keyPressed(KeyEvent e) {
    if (e.isActionKey())
      System.exit(0);
    System.out.println("The key Pressed was: " + e.getKeyChar());
  }
  @Override
  public void keyReleased(KeyEvent e) {
    System.out.println("The key Released was: " + e.getKeyChar());
  }
  public static void main(String[] args) {
    // Setting the Frame and Labels
    Frame f = new Frame("Demo");
    f.setLayout(new FlowLayout());
    f.setSize(500, 500);
    Label l = new Label();
    l.setText("This is a demonstration");
    f.add(l);
    f.setVisible(true);

    // Creating and adding the key listener
    KeyListenerExample k = new KeyListenerExample();
    f.addKeyListener(k);
  }
}

Output:

The key Pressed was: a
The key Typed was: a
The key Released was: a
The key Pressed was: b
The key Typed was: b
The key Released was: b

A Simple Game Application using KeyListener

Let’s create another program that will take the arrow keys as input. This program will move the number 0 to different locations in the matrix according to the key pressed. The output is printed to the console.

import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.Label;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.Arrays;
public class KeyListenerExample implements KeyListener {
  // Matrix and x, y coordinates of 0
  int[][] matrix;
  int x;
  int y;
  KeyListenerExample() {
    // Initializing the Matrix
    matrix = new int[3][3];
    matrix[0] = new int[] {1, 1, 1};
    matrix[1] = new int[] {1, 0, 1};
    matrix[2] = new int[] {1, 1, 1};

    x = 1;
    y = 1;

    // Printing the Matrix
    for (int i = 0; i < 3; i++) System.out.println(Arrays.toString(matrix[i]));
    System.out.println();
  }
  // keyPressed() method takes care of moving the zero according to the key pressed
  @Override
  public void keyPressed(KeyEvent e) {
    if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
      if (x != 2) {
        x += 1;
        System.out.println("Moving Right");
      } else
        System.out.println("Cannot Move Right");
    }
    if (e.getKeyCode() == KeyEvent.VK_LEFT) {
      if (x != 0) {
        x -= 1;
        System.out.println("Moving Left");
      } else
        System.out.println("Cannot Move Left");
    }
    if (e.getKeyCode() == KeyEvent.VK_DOWN) {
      if (y != 2) {
        y += 1;
        System.out.println("Moving Down");
      } else
        System.out.println("Cannot Move Down");
    }
    if (e.getKeyCode() == KeyEvent.VK_UP) {
      if (y != 0) {
        y -= 1;
        System.out.println("Moving Up");
      } else
        System.out.println("Cannot Move Up");
    }
    matrix[0] = new int[] {1, 1, 1};
    matrix[1] = new int[] {1, 1, 1};
    matrix[2] = new int[] {1, 1, 1};
    matrix[y][x] = 0;
    for (int i = 0; i < 3; i++) System.out.println(Arrays.toString(matrix[i]));
    System.out.println();
  }
  // We don't need the other two methods
  @Override
  public void keyReleased(KeyEvent e) {}
  @Override
  public void keyTyped(KeyEvent e) {}
  public static void main(String[] args) {
    // Setting the frame and labels
    Frame f = new Frame("Demo");
    f.setLayout(new FlowLayout());
    f.setSize(200, 200);
    Label l = new Label();
    l.setText("This is a Game");
    f.add(l);
    f.setVisible(true);

    // Creating and adding the key listener
    KeyListenerExample k = new KeyListenerExample();
    f.addKeyListener(k);
  }
}

Output:

[1, 1, 1]
[1, 0, 1]
[1, 1, 1]

Moving Right
[1, 1, 1]
[1, 1, 0]
[1, 1, 1]

Cannot Move Right
[1, 1, 1]
[1, 1, 0]
[1, 1, 1]

Moving Left
[1, 1, 1]
[1, 0, 1]
[1, 1, 1]

Moving Left
[1, 1, 1]
[0, 1, 1]
[1, 1, 1]

Cannot Move Left
[1, 1, 1]
[0, 1, 1]
[1, 1, 1]

Moving Up
[0, 1, 1]
[1, 1, 1]
[1, 1, 1]

Cannot Move Up
[0, 1, 1]
[1, 1, 1]
[1, 1, 1]

Moving Down
[1, 1, 1]
[0, 1, 1]
[1, 1, 1]

Moving Down
[1, 1, 1]
[1, 1, 1]
[0, 1, 1]

Cannot Move Down
[1, 1, 1]
[1, 1, 1]
[0, 1, 1]

Summary

Classes implement the KeyListener interface to listen and react to key events. In this tutorial, we learned a few important methods of the KeyEvent class. We also learned how to implement the KeyListener interface and how to override the keyPressed(), the keyReleased(), and the keyTyped() methods. We also saw a few examples that demonstrated the use of this interface.