Reputation: 4767
I'm implementing a class X that extends javax.swing.JFrame I added the inner class KeyInputHandler inside X with the following code:
private class KeyInputHandler extends KeyAdapter {
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_LEFT) {
}
if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
...
}
if (e.getKeyCode() == KeyEvent.VK_UP) {
...
}
if (e.getKeyCode() == KeyEvent.VK_SPACE) {
...
}
if (e.getKeyCode() == KeyEvent.VK_B) {
...
}
}
}
But for some reason it doesn't recognize my input. Do I have to add something else to the class X?
Upvotes: 1
Views: 169
Reputation: 285403
KeyListeners can be tricky, and most important, only work if the component they've been added to has the focus. Otherwise you're sunk. Also, you don't show in the code you've posted where you've added a KeyListener to any component yet. Yes, you have the class for it, but to you actually use the class to create an object and add it to anything?
But having said that, for your type of application and problem though, you're probably better off using key bindings (check out the link), a higher level concept that is more flexible when it comes to focus issues.
Edit
The question asked in comments was
What is focus?
Per the Focus Subsytem tutorial, when a GUI component is receiving keyboard input, it has the focus. Usually this is indicated by being highlighted in some way.
Upvotes: 3