KeyListener不会在JPanel上监听 [英] KeyListener won't listen on JPanel

查看:167
本文介绍了KeyListener不会在JPanel上监听的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个非常简单的程序,但是由于某些原因,当我调试它并在keyPressedkeyReleasedkeyTyped方法上设置断点时,该程序永远不会在那里停止.

It's a very simple program, but for some reason when I debug it and set breakpoints at the keyPressed, keyReleased and keyTyped method, the program never stops there.

    mainKeyListener = new KeyListener() {

        public void keyPressed(KeyEvent e) {
                System.out.println("KEY PRESSED");
                repaint();
            }
        }

        @Override
        public void keyReleased(KeyEvent arg0) {
            // TODO Auto-generated method stub

        }

        @Override
        public void keyTyped(KeyEvent arg0) {
            // TODO Auto-generated method stub

        }
    };

在这里,我将其添加到JPanel中,这是框架的确切大小,也是框架上唯一的对象:

Here I add it to a JPanel, which is the exact size of the frame and the only object on it:

    JPanel backgroundPanel = new JPanel();
    backgroundPanel.setBounds(0,0, 400, 500);
    backgroundPanel.addKeyListener(mainKeyListener);
    backgroundPanel.setFocusable(true);
    getContentPane().add(backgroundPanel);

推荐答案

您的问题出在重点关注的元素上.我认为您的小组失去了焦点.

Your problem is laying in focused element. I think that your panel lost the focus.

注意: 要触发键盘事件,组件必须具有键盘焦点.对于您的示例,可以通过多种方式解决此问题,您可以使用 KeyboardFocusManager 这样的示例:

Note: To fire keyboard events, a component must have the keyboard focus. It can be solved in many ways for your example you can use KeyboardFocusManager for example like this:

KeyboardFocusManager focusManager = KeyboardFocusManager.getCurrentKeyboardFocusManager();
        focusManager.addKeyEventDispatcher(new KeyEventDispatcher() {

            public boolean dispatchKeyEvent(KeyEvent e) {
                if(focusManager.getFocusOwner()!=backgroundPanel){
                                focusManager.redispatchEvent(backgroundPanel,e);
                                return true;}
                else return false;
            }
        });

还要尝试使用键绑定 http://docs.oracle. com/javase/tutorial/uiswing/misc/keybinding.html

这篇关于KeyListener不会在JPanel上监听的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆