繁体   English   中英

Java-如何将对象传递给KeyListener接口的实现?

[英]Java - how to pass objects to implementation of KeyListener interface?

我正在尝试实现KeyListener接口。 在实现中,我想根据键代码(keyPressed)和“ Player”对象以及一堆列表(在另一个类中创建)进行一些处理。 到目前为止,我一直将它们作为参数传递,但是现在我无法更改“ keyPressed”参数列表。 我唯一的想法是创建一个表示播放器和列表的静态字段,并通过ClassName.staticField访问它们,但这可能不是最好的主意。 我如何以更适当的方式访问它们?

public void keyPressed(KeyEvent e)
{
    int code = e.getKeyCode();
    //doing some stuff with code
    if(code == KeyEvent.VK_SHIFT)
        player.manipulateItem(/*few lists to pass here*/); //how to access the "player" object and lists?
}                                                           //they are created in another class as variables

最好在密钥侦听器的构造函数中传递播放器,但如果其值可以更改,则添加其容器。 举例:

public class A extends JFrame{
    final Player currentPlayer;
    public A(){
        currentPlayer = new Player();
        add(new JLabel("press to increase player score");
        addKeyListener(new MyKeyListener(currentPlayer));
        a.pack();
        a.setVisible(true);
    }

    private static final class MyKeyListener extends KeyAdapter{
         Player player;
         public MyKeyListener(Player player){
             super();
             this.player = player;  
         }

         @Override
         public void keyPressed(KeyEvent e) {
             int code = e.getKeyCode();
             //doing some stuff with code
             if(code == KeyEvent.VK_SHIFT)
                  player.manipulateItem(/*few lists to pass here*/);
             e.consume();
        }
    }
}

如果您的玩家不是最终玩家并且可以更改,请通过A实例并使用吸气剂。 如果您的听众是唯一的目标,别忘了消耗您的关键事件。 PS:对不起,导入丢失了我没有我的IDE跳下他们的手是没有错误的

暂无
暂无

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

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