KeyCodes for azerty keyboard in JAVA

1.5k views Asked by At

So I'm fairly new to Java programming and I'm trying to figure out how keyEventListeners work in Java. I've managed to make a tiny program in which you steer a red square, but the only problem is, it only works on a QWERTY-keyboard.

Here's the code that checks the keyCode:

public void keyPressed(KeyEvent e){
    int c = e.getKeyCode();

    if(c == KeyEvent.VK_LEFT){
        velX = -1;
        velY = 0;
    }
    if(c == KeyEvent.VK_UP){
        velX = 0;
        velY = -1;
    }
    if(c == KeyEvent.VK_RIGHT){
        velX = 1;
        velY = 0;
    }
    if(c == KeyEvent.VK_DOWN){
        velX = 0;
        velY = 1;
    }
}

How do I change this to azerty arrow keys, and (if possible) both? Thanks in advance.

1

There are 1 answers

1
Freek de Bruijn On BEST ANSWER

You could print the key codes you do not recognize, together with the key character (is probably not very helpful for the arrow keys). This way you could find out what the key codes on a different type of keyboard are.

Do the arrow keys have other key codes on an azerty keyboard or are those keys mapped to the same key codes (KeyEvent.VK_LEFT and the others)? If you have other key codes, you could add those to the if conditions.

In code:

public void customKeyPressed(KeyEvent e){
    int c = e.getKeyCode();

    if(c == KeyEvent.VK_LEFT || c == AZERTY_LEFT){
        velX = -1;
        velY = 0;
    } else if(c == KeyEvent.VK_UP || c == AZERTY_UP){
        velX = 0;
        velY = -1;
    } else if(c == KeyEvent.VK_RIGHT || c == AZERTY_RIGHT){
        velX = 1;
        velY = 0;
    } else if (c == KeyEvent.VK_DOWN || c == AZERTY_DOWN) {
        velX = 0;
        velY = 1;
    } else
        System.out.println(e.getKeyChar() + " = " + c);
}