Markus Tonsaker
Markus Tonsaker

Reputation: 479

Java - Slick2D: How to retrieve last key pressed?

After a lot of searching, I haven't found a easy solution to solve this.

I am incorporating a keybind settings section and I need to figure out when a user presses a key and which key is pressed.

I am using the Java Slick2D game engine. Slick2D java docs: http://slick.ninjacave.com/javadoc/

Example (Doesn't work):

private void setLastKey(GameContainer container){
    if(clickedRectangle != null){
        lastKeyPressed = container.getInput();
    }else{
        lastKeyPressed = null;
    }
}

Upvotes: 1

Views: 990

Answers (2)

Markus Tonsaker
Markus Tonsaker

Reputation: 479

Override keyPressed(int key, char c) in BasicGameState

private void setKeyBind(){
    if(clickedRectangle == null){
        lastKeyChar = '\u0000';
        lastKeyCode = 0;
    }
    if(lastKeyChar != '\u0000'){
        clickedRectangle = null;
    }
}

public void keyPressed(int key, char c){  //Overrides BasicGameState
    if(clickedRectangle != null && lastKeyChar == '\u0000'){
            lastKeyChar = c;
            lastKeyCode = key;
            System.out.println("Key: "+c + " KeyCode: "+key);
    }
}

Upvotes: 0

Anubian Noob
Anubian Noob

Reputation: 13596

In the update method, a GameContainer object is passed. You can use method container.getInput() to get an Input object. You can use that.

public void update(GameContainer container, StateBasedGame game, int delta) throws SlickException {
    if (container.getInput().isKeyPressed(Input.KEY_N))
        System.out.println("N key is pressed.");
}

Quoting a comment on this post:

You can't ask for what key is pressed because multiple can be.

Upvotes: 0

Related Questions