Keylistener 不适用于 JPanel [英] Keylistener not working for JPanel

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

问题描述

当使用 JPanel 类中的 KeyListener 按下其中一个箭头键时,我正在尝试执行某些操作.这是我的代码:

I am trying to do something when one of the arrow keys are pressed using the KeyListener in my JPanel class. Here is my code:

public class TestPanel extends JPanel implements KeyListener{

    public TestPanel(){
        this.addKeyListener(this);
        this.setFocusable(true);
        this.requestFocusInWindow();
    }

    public void keyPressed(KeyEvent e) {
        if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
            System.out.println("Right");

        }

        if (e.getKeyCode() == KeyEvent.VK_LEFT) {
            System.out.println("Left");
        }

    }

    public void keyTyped(KeyEvent e) {}
    public void keyReleased(KeyEvent e) {}
}

我的 main 方法将这个面板的一个新实例添加到一个框架中并显示它.我需要将密钥侦听器添加到 JFrame 吗?在我的情况下,这会很困难且效率低下,所以如果可能的话,我想让它与这个 JPanel 一起工作.有人知道我做错了什么吗?

My main method adds a new instance of this panel to a frame and displays it. Do I need to add the keylistener to the JFrame? In my case, this would be difficult and inefficient, so I would like to make it work with this JPanel if possible. Anyone know what I am doing wrong?

也不起作用的键绑定代码:

Key Bindings code that does not work either:

public class GamePanel extends JPanel implements ActionListener{

//Constructor
public GamePanel(){

    setupKeyBinding();
    this.setFocusable(true);
    this.requestFocusInWindow();


}

private void setupKeyBinding() {
    int condition = JComponent.WHEN_IN_FOCUSED_WINDOW;
    InputMap inMap = getInputMap(condition);
    ActionMap actMap = getActionMap();

    inMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0), "Left");
    actMap.put("Left", new leftAction());
}

private class leftAction extends AbstractAction {

       public void actionPerformed(ActionEvent e) {
          System.out.println("test");
       }
}

public void actionPerformed(ActionEvent e) {
    //some other game info
}
} 

谁能告诉我为什么这也不起作用?(我的第二个动作监听器用于我的游戏所需的其他内容)

Can someone tell me why this doesnt work either? (my second action listener is for other stuff needed for my game)

推荐答案

如果你搜索这个问题,你会看到它被问过很多次并且已经解决了很多次.

If you search this problem, you'll see that it is asked and has been solved many times.

  • KeyListeners 需要在焦点组件上才能工作.一种解决方案是在首先使组件具有焦点之后再给它焦点.
  • 远景更好的是使用键绑定.谷歌有关这方面的教程.

请查看我对这个问题的回答,了解更多相关信息,包括许多血腥的细节.

Please have a look at my answer to this question for more on this, including many of the gory details.

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

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