首先永远不要使用数字常量而不是字段常量,
public void keyPressed(KeyEvent k) {
int keyCode = k.getKeyCode();
if(keyCode == KeyEvent.VK_R) // not keyCode == 82
}
更好的方法是使用 InputMap 和 ActionMap,我认为这也称为“键绑定”(正如 MadProgrammer 所建议的那样)。输入映射将击键映射到动作名称,动作映射将动作名称映射到您要执行的动作。
替换您的线路(以及整个 KeyListener 扩展类)
this.addKeyListener(new MyKeyListener());
类似的东西
this.getInputMap().put(KeyStroke.getKeyStroke("control L"), "link");
您需要参考KeyStroke.getKeyStroke的文档来根据您的需要修改指定的击键。在我的示例中,“链接”是按下 CTRL+L 时要执行的操作的名称。现在我们需要指定“链接的作用”
this.getActionMap().put("link", new LinkAction());
LinkAction 是我的类扩展 AbstractAction,在您的情况下应该包括您的方法,例如 levelReaderObject.setCurrentLevel(presentLevel);。
请注意,您不需要为每个键创建一个操作。对于移动(上、下、左、右),我会将所有移动按钮绑定到不同的动作名称(“上移”等),然后将所有动作名称映射到同一个动作,并让该动作中的方法做这项工作:
this.getActionMap().put("move up", new MoveAction(0));
this.getActionMap().put("move down", new MoveAction(1));
this.getActionMap().put("move right", new MoveAction(2));
this.getActionMap().put("move left", new MoveAction(3));
与
class MoveAction extends AbstractAction {
int direction;
public MoveAction (int direction) {
this.direction = direction;
}
@Override
public void actionPerformed(ActionEvent e) {
switch(direction) // perform the action according to the direction
}
}
请注意,我将移动动作组合在一起的建议是一项设计决策,您应该自己决定如何构建绑定(您可以对所有内容使用一个动作,也可以对每个动作使用一个动作)。