1

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?

2
  • Can you post working code? just creating the class doesn't automatically mean it gets called. Commented Nov 25, 2011 at 22:16
  • 1
    stackoverflow.com/questions/5048536/… Did you call addKeyListener? Commented Nov 25, 2011 at 22:18

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.