edit:该线程被标记为重复。但是我是一个初学者,链接的主题对我没有帮助...我有一个新主意(请参阅下面的“ 新主意”下的内容),但我也没有使它起作用。
我有一个简单的代码可以识别按下的按钮:
class KeyboardInput{
KeyboardInput(JPanel panel){
InputMap inMap = panel.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
ActionMap actMap = panel.getActionMap();
//W
inMap.put(KeyStroke.getKeyStroke("W"), "MoveForward");
actMap.put("MoveForward", new WAction());
//A
inMap.put(KeyStroke.getKeyStroke("A"), "TurnLeft");
actMap.put("TurnLeft", new AAction());
//S
inMap.put(KeyStroke.getKeyStroke("S"), "TurnAround");
actMap.put("TurnAround", new SAction());
//D
inMap.put(KeyStroke.getKeyStroke("D"), "TurnRight");
actMap.put("TurnRight", new DAction());
}
//W
class WAction extends AbstractAction {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("W"); //test purpose
Generate.action = "f";
System.out.println(Generate.action); //test purpose
}
}
//A
class AAction extends AbstractAction {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("A");
Generate.action = "l";
}
}
//S
class SAction extends AbstractAction {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("S");
Generate.action = "b";
}
}
//D
class DAction extends AbstractAction {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("D");
Generate.action = "r";
}
}
}
我得到了期望的输出和Generate.action更新。类Generate具有一个大的while循环,该循环根据String动作执行操作。
最初,该循环通过java.util.Scanner请求更新操作,然后该循环完成了它的工作。但是,由于键盘输入W / A / S / D,我如何告诉while循环重新开始动作?
新想法:
我试图让while循环等到动作被更新。像这样:
boolean condition = false;
action = "empty"; //action is static.
while((condition == false)) {
while(action.equals("empty") {
(...) //wait until W, A, S or D is pressed/action changed.
}
if (action.equals("f") {
(...) //do something
}
if (action.equals("l") {
(...) //do something
}
(...)
//reset action to start loop again.
action == "empty";
}
}
有没有办法做到这一点?