Search code examples
javaswingkeylistenerkeycodekeystroke

Trouble with KeyEvent and KeyStroke


I noticed that I get two different keyCode for the same Char. Here is a little experiment:

package main;

import com.sun.javafx.scene.control.Keystroke;

import javax.swing.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

public class Keystroketest {
    public static void main(String[] args) {
        final KeyStroke ks = KeyStroke.getKeyStroke('e', 0);
        System.out.println(ks.getKeyCode());

        JFrame f = new JFrame();
        JTextField jtf = new JTextField("");
        f.setBounds(300, 300, 100, 60);
        f.add(jtf);
        f.setVisible(true);


        jtf.addKeyListener(new KeyListener() {
            @Override
            public void keyTyped(KeyEvent keyEvent) {
            }

            @Override
            public void keyPressed(KeyEvent keyEvent) {
            }

            @Override
            public void keyReleased(KeyEvent keyEvent) {
                System.out.println(keyEvent.getKeyCode());
                if (keyEvent.getKeyCode() == ks.getKeyCode()) {
                    System.out.println("letters are similar");
                } else {
                    System.out.println("letters aren't similar");
                }
            }
        });
    }
}

If I type in the textField the letter "e" so it returns a different KeyCode for the same letter when I parse it.

Whats the reason? And how can I check if the letter/char I typed is the same as in a specific char defined in the code as above...?

So whenever I check the KeyCode I typed, java thinks I didn't type the same letter. But that's not correct I think.


Solution

  • You are using the wrong getKeyStroke method:

    final KeyStroke ks = KeyStroke.getKeyStroke('e', 0);
    

    Calls getKeyStroke(int keyCode, int modifiers), since a "char" is interpreted as a 16 bit value that can be autocast to a 32 bit int value. Autoboxing does only happen if there isn't a fitting method.

    use either

    final KeyStroke ks = KeyStroke.getKeyStroke(Character.valueOf('e'), 0);
    

    or:

    final KeyStroke ks = KeyStroke.getKeyStroke('e');
    

    And remember for your own APIs: try to detect such clashes when overloading. ;-)

    Also, like MadProgrammer pointed out that won't resolve your problem.

    Have you tried using keyEvent.getKeyChar() instead?