Slick2D's Input class has a isKeyPressed() method that returns a boolean value according to whether the specified key has been pressed. I want to check if a key has been released in the same fashion.

I looked into adding a KeyListener to the input object, and overriding the keyReleased() method. However, because I am currently handling input in the update() method of my BasicGame, this would fracture my code by handling input in two different places, which I'd like to avoid.


1 Answer 1


So you've got callbacks, but you really want state.

Here's an adapter:

Every frame (or on callbacks), update an associative map (HashMap in Java lingo) that maps from key codes to a status of whether that key was just pressed, is held down or was just released.

// In a `GameState` class

    // Turn "released" keys off and "pressed" keys "held"
    for k,status of keys
        if status is "pressed"  then keys[k] = "held"
        if status is "released" then keys[k] = null
        // otherwise stay the same

    keys[k] = "pressed"

    keys[k] = "released"

Then interrogate that map from everywhere else that cares.

In Java, it'll likely be faster and more readable by refactoring all the state Strings to Enums, but this is is the idea. Of course, implementing getKeyReleased is then a HashMap-access one-liner.

  • \$\begingroup\$ Very cool. I like this solution. \$\endgroup\$ Mar 8, 2014 at 20:30

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .