Maciej Cygan Maciej Cygan - 11 months ago 39
Java Question

KeyEvent not recognizing that shift is pressed

I am having following problem, i am trying to restrict users to enter only alphabetical values. Any other value (key pressed) that is not alphabetical will throw error. There are however 3 exceptions, of which two are working fine.
exception1 : Del Key
exception2 : Back Key
exception3 : Shift <- this one is not recognized and i am not sure why

SurnameSearch.addKeyListener(new KeyAdapter(){
public void keyPressed(KeyEvent e){
char ch = e.getKeyChar();
if(Character.isAlphabetic(ch)|| (ch == KeyEvent.VK_BACK_SPACE) || (ch == KeyEvent.VK_DELETE) || (ch == KeyEvent.VK_SHIFT)){/*null*/}
JOptionPane.showMessageDialog(null, "Only letters are allowed!");
SurnameSearch.setText(" ");

Hints appreciated :)


Example would be, a user is requested to enter into form his surname, first name, middle name, and mobile telephone number && home phone number. So obviously we dont want numerical values in alphabetic field and vice verse :)

Answer Source

That's because the Shift key doesn't have a Unicode key character. It's probably returning KeyEvent.VK_UNDEFINED. Rather, the Shift key modifies other keypresses (i.e., it capitalizes them, usually).

From the Javadoc, getKeyChar:

Returns the character associated with the key in this event. For example, the KEY_TYPED event for shift + "a" returns the value for "A".

Instead of using getKeyChar, try getKeyCode, which

Returns the integer keyCode associated with the key in this event.

You will probably also have to use getKeyChar for your isAlphabetic presses (if those matter to you).

EDIT: Here's a working example:

public static void main(String[] args) {
    JFrame f = new JFrame();
    JButton button = new JButton("Press keys");
    button.addKeyListener(new KeyAdapter() {

        public void keyPressed(KeyEvent ke) {
            if (ke.getKeyCode() == KeyEvent.VK_SHIFT) {
                System.out.println("You pressed Shift");
            } else {
                System.out.println("You pressed a non-Shift key");
                // [ more logic ]

    f.add(button, BorderLayout.CENTER);