我最近开始研究我一直在创建的原始游戏的用户界面。它有一个例外。我目前正在使用Keystroke类来获取输入而不是键事件。
public void bindControls()
{
inputMap = frame.getMainPane().getInputMap(IFW);
actionMap = frame.getMainPane().getActionMap();
inputMap.put(KeyStroke.getKeyStroke("UP"), Controls.UP_ACTION);
inputMap.put(KeyStroke.getKeyStroke("DOWN"), Controls.DOWN_ACTION);
inputMap.put(KeyStroke.getKeyStroke("LEFT"), Controls.LEFT_ACTION);
inputMap.put(KeyStroke.getKeyStroke("RIGHT"), Controls.RIGHT_ACTION);
inputMap.put(KeyStroke.getKeyStroke("W"), Controls.UP_ACTION);
inputMap.put(KeyStroke.getKeyStroke("S"), Controls.DOWN_ACTION);
inputMap.put(KeyStroke.getKeyStroke("A"), Controls.LEFT_ACTION);
inputMap.put(KeyStroke.getKeyStroke("D"), Controls.RIGHT_ACTION);
actionMap.put(Controls.UP_ACTION, new MoveAction(Controls.UP_ACTION));
actionMap.put(Controls.DOWN_ACTION, new MoveAction(Controls.DOWN_ACTION));
actionMap.put(Controls.LEFT_ACTION, new MoveAction(Controls.LEFT_ACTION));
actionMap.put(Controls.RIGHT_ACTION, new MoveAction(Controls.RIGHT_ACTION));
}
这是我运行以绑定播放器控件的方法。 我的问题是" W"," A"," S"和" D"一切正常,但是" UP"," DOWN"," LEFT"和" RIGHT"。按下时什么都不做。我随处可见,包括java文档。但我读过的所有内容都声称上面的代码是正确的。
如果有人遇到此问题或有解决方法,我可以使用您的帮助。 谢谢!
P.S。 Controls.java是一个枚举
package controls;
public enum Controls
{
UP_ACTION, DOWN_ACTION, LEFT_ACTION, RIGHT_ACTION
}
编辑:我的MoveAction类
package controls;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
public class MoveAction extends AbstractAction
{
private static final long serialVersionUID = 1L;
Controls direction;
public MoveAction(Controls direction)
{
this.direction = direction;
}
@Override
public void actionPerformed(ActionEvent e)
{
if(direction == Controls.UP_ACTION)
{
up();
}
else if(direction == Controls.DOWN_ACTION)
{
down();
}
else if(direction == Controls.LEFT_ACTION)
{
left();
}
else if(direction == Controls.RIGHT_ACTION)
{
right();
}
System.out.println(direction);
}
public void up()
{
}
public void down()
{
}
public void left()
{
}
public void right()
{
}
}
答案 0 :(得分:0)
感谢@Zachary的回答。 它是
(KeyEvent.VK_UP, 0)
不是
("UP")
我仍然不知道为什么会这样,因为它似乎都适用于其他用户。但是这样可行,所以我会接受它。