Question

I've made a key listener for my app and I need to identify the key code when the user presses the shift key + a key.

For example, when the user presses the shift key + the key 2 (English keyboard), it should print @. I made a quick switch/case to identify which is the shifted key, but it doesn't work on azerty keyboards nor mac ones.

Is there a way in java to get the shifted key or something?

It's quite hard to explain.

My java app just get the keycode, what i need is the shifted keycode associated to a keycode.

ex:

  • (QWERTY) 2 => @; 3 => #; etc...
  • (AZERTY) & => 1; é => 2; etc...

For the moment, my code is like that (Only works for qwerty KB)

String value = String.valueOf((char)key);
    if (shift)
    {
        switch (value.charAt(0))
        {
            case '1':
                return "!";
            case '2':
                return "@";
            case '3':
                return "#";

            .....

Thanks for your help.

Regards.

Was it helpful?

Solution 3

Finally, I made a frame that allows user to select his keyboard layout. Then I just made a simple swith/case to get the shifted key.

String value = String.valueOf((char)key);
if (shift && keyboard.equals("QWERTY"))
{
    switch (value.charAt(0))
    {
        case '1':
            return "!";
        case '2':
            return "@";
        case '3':
            return "#";
    }
}
else if (shift && keyboard.equals("AZERTY"))
{
    switch (value.charAt(0))
    {
        case '&':
            return "1";
        case 'é':
            return "2";
        case '"':
            return "3";
    }
}
else return value;

I hope this could help someone else.

Regards.

OTHER TIPS

Try using KeyEvent#getKeyChar(). For an event Shift+a, this returns A. But this only works in the KeyListener#keyTyped() method, not in the other ones (keyReleased/keyPressed). Here is a little example, that works very well. I tried different keyboard layouts. Your example (Shift+2) return @ in qwerty, etc.

import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

import javax.swing.JFrame;

public class Maion {
    public static void main(String[] args) {
        JFrame frame = new JFrame();
        frame.setSize(600, 400);
        frame.addKeyListener(new KeyAdapter() {
            @Override
            public void keyTyped(KeyEvent e) {
                System.out.println("keyTyped: '" + e.getKeyChar() + "'");
            }
        });
        frame.setVisible(true);
    }
}

Look at the method getModifiers() in the class KeyEvent. This will tell you which special keys are pressed (Alt, Ctrl, Shift)

Example:

boolean oneShift = (keyEvent.getKeyCode() == KeyEvent.VK_1) && "Shift".equals(KeyEvent.getKeyModifiersText(keyEvent.getModifiers()))
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top