java - Java - 如何将对象传递给 KeyListener 接口的实现?
问题描述
我正在尝试实现 KeyListener 接口。在实现中,我想根据键代码(keyPressed)用我的“播放器”对象和一堆列表来做一些事情,这些列表是在另一个类中创建的。到目前为止,我将它们作为参数传递,但现在我无法更改“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 的实例并使用 getter。如果您的听众是唯一的目标,请不要忘记使用您的关键事件。PS:抱歉导入丢失我没有我的IDE,他们没有错误
推荐阅读
- macros - 测试元谓词映射表的目标扩展
- swift - 子类化 UIButton 给我错误
- firebase - 如何在另一个 Flutter 页面上更新 Firestore 数据
- python - 如何使用 Django 以表格形式发布好帖子
- sql - 如果 Field1 中的值为 null,则从 Field2 返回值,否则返回 String
- python - 在 Python 3.6 中安装和导入 tensorflow 时遇到问题
- reactjs - 对语义 UI 多搜索下拉问题做出反应
- html - 使用 Bootstrap 3 重新排序 div
- function - 在函数中使用未初始化的变量?
- android - 反应本机弹出