public void buttons(){
int c = WHEN_IN_FOCUSED_WINDOW;
Action right = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
player.setVX(2);
}
};
Action stop = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
player.setVX(0);
player.setVY(0);
}
};
Action up = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
player.setVY(-2);
}
};
getInputMap(c).put(KeyStroke.getKeyStroke("D"), "pressed");
getActionMap().put("pressed", right);
getInputMap(c).put(KeyStroke.getKeyStroke("released D"), "released");
getActionMap().put("released", stop);
getInputMap(c).put(KeyStroke.getKeyStroke("W"), "pressed");
getActionMap().put("pressed", up);
getInputMap(c).put(KeyStroke.getKeyStroke("released W"), "released");
getActionMap().put("released", stop);
}
为什么当我按下W或D时它会上升...
有什么问题?
D应该是正确的
答案 0 :(得分:4)
您正在覆盖动作地图中的值,因为您正在使用相同的操作名称“按下”进行向上和向右操作。
getInputMap(c).put(KeyStroke.getKeyStroke("D"), "pressed");
getActionMap().put("pressed", right);
getInputMap(c).put(KeyStroke.getKeyStroke("released D"), "released");
getActionMap().put("released", stop);
getInputMap(c).put(KeyStroke.getKeyStroke("W"), "pressed");
getActionMap().put("pressed", up); // this overwrites the "pressed" action name above with the up action
getInputMap(c).put(KeyStroke.getKeyStroke("released W"), "released");
getActionMap().put("released", stop); // similarly, this is redundant because you have the same thing above
以下内容应该解决它:
getInputMap(c).put(KeyStroke.getKeyStroke("D"), "right");
getInputMap(c).put(KeyStroke.getKeyStroke("released D"), "stop");
getInputMap(c).put(KeyStroke.getKeyStroke("W"), "up");
getInputMap(c).put(KeyStroke.getKeyStroke("released W"), "stop");
getActionMap().put("right", right);
getActionMap().put("up", up);
getActionMap().put("stop", stop);