Search code examples
javaswingswitch-statementjpaneluser-input

Java Switch with user input keystrokes


I'm making a snake game in Java and need to use user keystrokes to control the direction of the movement. Is this possible through a switch statement? I was originally using a Scanner s = new Scanner(System.in) to allow user to type 'u','d', etc. to move snake, but I would like to use the keyboard arrows instead.

Here is what I have right now:

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;
    } 

}

I was going to insert something like this, but not sure how to:

     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);

     }
     });

What would be the best way to accomplish this?


Solution

  • I see you are using Swing. You can make use of KeyListener interface. Something like this.

    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.
                }
        });