Key Event in Java Swing

In Java Swing, a key event refers to an event that occurs when the user interacts with the keyboard. Specifically, a key event is generated when a key is pressed, released, or typed (i.e., a key is pressed and then released).

When a key event occurs, Swing generates an object of the KeyEvent class, which contains information about the event, such as the key code of the pressed key, the state of the keyboard modifiers (e.g., Ctrl, Shift, Alt), and the source component that received the event.

To handle key events in a Swing component, we need to implement the KeyListener interface and override its three methods: keyPressed(), keyReleased(), and keyTyped(). These methods are called by Swing when a key event occurs, and we can write code to perform specific actions based on the key event.

In this post, we will create a JFrame with a JPanel and a JLabel. We will implement the KeyListener interface to handle key events, and add the listener to the JFrame using the addKeyListener method. We will also set the frame to be focusable so that it can receive key events.

Example

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

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class KeyEventDemo extends JFrame implements KeyListener {

	private JPanel panel;
	private JLabel label;

	public KeyEventDemo() {
        panel = new JPanel();
        label = new JLabel("Press a key");

        panel.add(label);
        add(panel);

        addKeyListener(this);
        setFocusable(true);

        setTitle("Key Example");
        setSize(300, 200);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);
        setVisible(true);
    }

	@Override
	public void keyPressed(KeyEvent e) {
		label.setText("Key Pressed: " + KeyEvent.getKeyText(e.getKeyCode()));
	}

	@Override
	public void keyReleased(KeyEvent e) {
		label.setText("Key Released: " + KeyEvent.getKeyText(e.getKeyCode()));
	}

	@Override
	public void keyTyped(KeyEvent e) {
		label.setText("Key Typed: " + e.getKeyChar());
	}

	public static void main(String[] args) {
		new KeyEventDemo();
	}

}

The keyPressed, keyReleased, and keyTyped methods will be called when a key is pressed, released, or typed, respectively. After the event, it updates the text of the JLabel in each method to display information about the key event.

When we run this program, we should see a window with the text “Press a key”. When we press, release, or type a key, the text of the label should update to show information about the key event.

Output

Key Event in Java Swing KeyEvent output 1

I pressed the different keys like C, D and that event also occurred before I released it. You can see the different events shown in the below image. These events are generated when I press the keys on my laptop keyboard.

Key Event in Java Swing Key Event Demo
Sharing Is Caring: