2

I working on a java application. I want to implement a KeyListener, on the arrows key. I have a class that extends JFrame and implements ActionListener

public class MyClass extends JFrame implements ActionListener{
}

How can I add a keyboard listener on the arrow keys in this frame?

I tried to do the following in the constructor, but it did not work:

    this.addKeyListener(new KeyListener() {

        @Override
        public void keyPressed(KeyEvent e) {
            if(e.getKeyCode() == KeyEvent.VK_UP)
            {
               //DO Some things
            }
        }

        @Override
        public void keyTyped(KeyEvent e) {

        }

        @Override
        public void keyReleased(KeyEvent e) {

        }

    });

Any help is greatly appreciated. Thanks

mKorbel
  • 109,525
  • 20
  • 134
  • 319
Y2theZ
  • 10,162
  • 38
  • 131
  • 200

1 Answers1

5

This can be solved by giving your JFrame the focus after making it focusable, but once it loses focus, the KeyListener will fail to work. My main suggestion is that you don't use a KeyListener but rather use Key Bindings as these function are higher level constructs and work well with Swing applications, especially with respect to gaining and losing focus. There are many similar posts on this subject, and if you hang on, I'll get you some links.

Community
  • 1
  • 1
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373