# How can I make the code run only once when I release the key?

Im making a game in LWJGL 2 and Slick2d. Im trying to add an item to my inventory by releasing a key (the inventory system works properly, the part where I have to see if the button was RELEASED is difficult). Right now when I do...

if (Keyboard.getEventKey() == Keyboard.KEY_L) {
if(Keyboard.getEventKeyState() == false){
}
}


... In my update method, Instead of it only calling the 2nd if statement once, ( because you can only release a key once) It just keeps going because the getEventKeyState variable stays false, but if Ive already released it once it should switch back to the opposite. Although I can do it by making it add an item when i hold the key, I cant exactly make it add only the 1 item, it keeps adding items while I hold it.

public static void addItem(int id){
for(InventorySlot s : inventoryslots){
if(s.getItem() == -1){
s.setItem(id);
System.out.println("Added item " + id + "!");
break;
}
}
}


Thats the addItem method, and if I would approach this by making it add the item while holding, I would have to make it so that it adds it only once. Any suggestions please? Thank you

• Your problem lies in your keyreleased event. When you hold a key, it calls the keypressed event every frame update as long as the key is held down. When you call keyreleased, your key state will be false as long as you aren't pressing the key. I believe Slick2D recommends using @Vokail 's answer. See slick.ninjacave.com/wiki/index.php?title=Input Aug 16 '16 at 12:28
• Also, if you do insist on using keystates, which are recommended by LWJGL and technically more useful, I would recommend reading (or rereading) wiki.lwjgl.org/wiki/LWJGL_Basics_2_(Input). You really need to be bounding your input with "while(Keyboard.next()) {...}" and I would recommend switching the order of the if-statements in the code you posted just for clarity. Aug 16 '16 at 12:33
• @NathanielD.Hoffman Looks like you know enough that you could create a decent answer out of this! Jan 24 '20 at 2:51
• @Vaillancourt I've posted an answer, after looking over this question and trying to refresh my memory. As it turns out, all of OP's code posted above works fine by itself, but there is a loop that needs to go around it in order to remove events from the key register. Jan 24 '20 at 4:30

The problem here is (likely) really simple. You need to call Keyboard.next() in order to pop the "L key was released" item out of the Keyboard queue, otherwise it'll just stick around in there.
container.getInput().isKeyPressed(Input.KEY_SPACE)