Domanda

I am trying to create a simple game in a java applet, and I need to have my character move around (in four directions) using either the arrow keys or wasd (either should work). I was unable to use arrows, so I tried this, which uses the capitol letters WASD instead:

public void keyPressed(KeyEvent e) {

    char c = e.getKeyChar();

    if ( (c == KeyEvent.VK_W) || (c == KeyEvent.VK_A) || (c == KeyEvent.VK_S) || (c == KeyEvent.VK_D) )
    {
        setboard();
    }
}

This works exactly how I want it to, but it is tedious to have to turn on caps lock every time I run the program.

How can I change this program so that the KeyListener can sense lowercase letters and the arrow keys? VK_UP, VK_DOWN, VK_w, VK_a, etc. doesn't work.

È stato utile?

Soluzione

To use the arrows, you're going to need to use getKeyCode(), which returns an int. Doing it this way solves your capital letters problem, too. Like this:

int code = e.getKeyCode();

if (code == KeyEvent.VK_W) {
    //do stuff
    //repeat with VK_A, VK_S, and VK_D
}

All the KeyEvent constants are ints underneath the hood anyway.

Altri suggerimenti

You can convert the char to uppercase before comparison, so it wont matter if upper or lowercase:

 char c = Character.toUpperCase(e.getKeyChar());
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top