Java开关与用户输入击键

我正在Java中做蛇游戏,需要使用用户击键来控制移动的方向。这可能通过switch声明吗?我最初使用Scanner s = new Scanner(System.in)来允许用户输入'u','d'等来移动蛇,但我想用键盘箭头代替。Java开关与用户输入击键

这是我现在所拥有的:

public void controlSnake(){ 

Scanner s = new Scanner(System.in);

String inputString = s.next();

switch (inputString) {

case "u":

case "U":

snake.changeDirection(Point.NORTH);

break;

case "d":

case "D":

snake.changeDirection(Point.SOUTH);

break;

case "r":

case "R":

snake.changeDirection(Point.EAST);

break;

case "l":

case "L":

snake.changeDirection(Point.WEST);

break;

}

}

我要插入这样的事情,但不知道如何:

 map1.put(KeyStroke.getKeyStroke("LEFT"), "moveLeft"); 

getActionMap().put("moveLeft", new AbstractAction() {

private static final long serialVersionUID = 1L;

public void actionPerformed(ActionEvent e) {

snake.changeDirection(Point.WEST);

}

});

什么是做到这一点的最好办法?

回答:

我看到你在使用Swing。您可以使用KeyListener接口。像这样的东西。

yourButton.addKeyListener(new KeyListener(){ 

@Override

public void keyPressed(KeyEvent e) {

if(e.getKeyCode() == KeyEvent.VK_UP){

snake.changeDirection(Point.NORTH);

}

if(e.getKeyCode() == KeyEvent.VK_DOWN){

snake.changeDirection(Point.SOUTH);

}

//Likewise for left and right arrows

}

@Override

public void keyTyped(KeyEvent e) {

throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.

}

@Override

public void keyReleased(KeyEvent e) {

throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.

}

});

回答:

它可以从JDK 7使用switch语句与String

Strings in switch Statements

,似乎你正在开发一个控制台游戏。如果您使用的秋千,您可以考虑使用InputMap连同ActionMap代替:

How to Use Key Bindings

以上是 Java开关与用户输入击键 的全部内容, 来源链接: utcz.com/qa/259613.html

回到顶部