Keylistener不为JPanel工作
我正在尝试使用我的JPanel类中的KeyListener按下其中一个箭头键时执行某些操作。这是我的代码:
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方法将一个新面板实例添加到一个框架并显示它。我需要将keylistener添加到JFrame吗?在我的情况下,这将是困难和低效的,所以如果可能的话,我想让它与这个JPanel一起工作。谁知道我做错了什么?
编辑:键绑定代码不起作用:
public class GamePanel extends JPanel implements ActionListener{//Constructorpublic 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}}谁能告诉我为什么这也不起作用?(我的第二个动作听众是我游戏所需的其他东西)
 MM们
MM们 
					呼唤远方
 随时随地看视频慕课网APP
随时随地看视频慕课网APP
相关分类