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()
andKeyEvent.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.
Be sure to include
jframe.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
before the end of psvm, otherwise the JFrame will close, but not exit properly.
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?