简体   繁体   English

将Arrow Keylistener添加到实现ActionListener的Jframe中

[英]Add Arrow Keylistener to a Jframe that implements ActionListener

I working on a java application. 我正在研究Java应用程序。 I want to implement a KeyListener, on the arrows key. 我想在箭头键上实现KeyListener。 I have a class that extends JFrame and implements ActionListener 我有一个扩展JFrame并实现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 谢谢

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. 可以通过在使JFrame成为焦点之后为JFrame赋予焦点来解决此问题,但是一旦失去焦点,KeyListener将无法工作。 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. 我的主要建议是您不使用KeyListener而是使用Key Bindings,因为这些函数是更高级别的构造,并且可以与Swing应用程序很好地配合,尤其是在获得和失去焦点方面。 There are many similar posts on this subject, and if you hang on, I'll get you some links. 关于这个主题有很多类似的帖子,如果您坚持下去,我会给您一些链接。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM