event
Handle key presses example
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
KeyAdapter
instance. - 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()
andKeyEvent.getKeyCode()
to find out which key the user pressed.
Let’s take a look at the code snippet that follows:
package com.javacodegeeks.snippets.desktop;
import java.awt.BorderLayout; import java.awt.Component; import java.awt.Frame; import java.awt.TextArea; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; public class KeyListener { public static void main(String[] args) { // Create frame with specific title Frame frame = new Frame("Example Frame"); // Create a component to add to the frame; in this case a text area with sample text Component textArea = new TextArea("You pressed []: n"); textArea.addKeyListener(new KeyAdapter() { public void keyPressed(KeyEvent evt) { TextArea source = (TextArea)evt.getSource(); source.setText("You pressed [" + evt.getKeyText(evt.getKeyCode()) +"] : "); } }); // Add the components to the frame; by default, the frame has a border layout frame.add(textArea, BorderLayout.NORTH); // Show the frame int width = 300; int height = 300; frame.setSize(width, height); frame.setVisible(true); } }
This was an example on how to handle key presses in Java.