Search code examples
javaconstantskeyevent

KeyEvent Constants in Java


I came across this code:

    private boolean right = true;
    public void keyPressed(KeyEvent e) {

                    int key = e.getKeyCode();

                    if ((key == KeyEvent.VK_LEFT) && (!right)) {
                        left = true;
                        up = false;
                        down = false;
                    }

    }

From my understanding, the getter method called getKeyCode returns a key in integer form. Does a programmer necessarily have to understand the actual numerical value of KeyEvent.VK_LEFT? Or should I treat it as a black box and not care and worry about how it is implemented and just use it?

Apparently the value associated with VK_LEFT is 37 after looking at the Java API.


Solution

  • The point about those constants is that you don't have to know the actual numeric value. You could get it easily with a println but you shouldn't (you're not ensured the value won't change in a future release).

    Treat them as black boxes.