Java KeyEvent comparison - is arg0 equal to a specific key

comparison, java, keyevent, keylistener

Solution

To compare the input with `KeyEvent.xxx` values, you need to use the `getKeyCode` method, which returns an `int` when you capture `keyPressed` or `keyReleased` events - you can then compare the value with a `KeyEvent.xxx`. If you want to use a `keyTyped` event, you can use the `getKeyChar` method but it will not capture some keys (action or modifier keys for example) - this should work for example:

public void keyReleased(KeyEvent e) {
    if (e.getKeyCode() == KeyEvent.VK_ENTER || e.getKeyCode() == KeyEvent.VK_R) {
        System.out.println("Enter or R key typed.");
    } else {
        System.out.println("Something else typed.");
    }
}

Problem

I have created a new KeyListener, defined as following: ``` ... public void keyTyped(KeyEvent arg0) { if (arg0.equals(KeyEvent.VK_ENTER) || (arg0.equals(KeyEvent.VK_R))) { System.out.println("Enter or R key typed."); } else { System.out.println("Something else typed."); } } ... ``` What I actually want to do is to call a method every time when the Enter key or 'R' is typed in. My Problem: No matter what I type in, the if case is never triggered. It always jumps to the else case. What it the reason for this behaviour?

Original source