本文介绍了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) {}
}

我的主要方法将此面板的新实例添加到框架并显示它。我是否需要将keylistener添加到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需要在焦点组件上工作。一个解决方案是在首次使其成为焦点之后为您的组件提供焦点。

  • 然而,更好的方法是使用Key Bindings。谷歌有关这方面的教程。

请查看我对了解更多相关信息,包括许多血腥细节。

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

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

07-12 03:35