Stanislav Bulavskiy
Stanislav Bulavskiy

Reputation: 13

How to get any pressed key value

I'm trying to develop sort of typing trainer using libgdx and stuck with this kind of problem. I need a way to detect what key user pressed to rather display it (if it was a letter) or clear input (if it was space key). I've come up with this solution:

StringBuilder typeArea = new StringBuilder();
if (Gdx.input.isKeyJustPressed(Input.Keys.A)) {
    typeArea.append(Input.Keys.toString(Input.Keys.A));
} else if (Gdx.input.isKeyJustPressed(Input.Keys.B)) {
    typeArea.append(Input.Keys.toString(Input.Keys.B));
} else if ... {
          ...
} else if (Gdx.input.isKeyJustPressed(Input.Keys.SPACE)) {
    typeArea.setLength(0);
}

Feels like there should be more elegant way. I'm looking for something like this:

String letters = "abcdefg...";
StringBuilder typeArea = new StringBuilder();
if (Gdx.input.isKeyJustPressed(Input.Keys.ANY_KEY)) {
    if (letters.indexOf(getKeyPressedValue()) >= 0) {
        typeArea.append(getPressedKeyValue());
    } else if (getKeyPressedValue() == Input.Keys.SPACE) {
        typeArea.setLength(0);
    }
} 

Or maybe there is another simpler way to do this. Any suggestions?

Upvotes: 1

Views: 1035

Answers (1)

dfour
dfour

Reputation: 1376

You can create your own InputListener and override the keyDown method which sends the keycode with the event.

InputListener il = new InputListener(){
        @Override
        public boolean keyDown(InputEvent event, int keycode) {
                typeArea.append(Keys.toString(keycode));
            return super.keyDown(event, keycode);
        }
    };

Or you could implement an InputProcessor and use the Override the KeyDown method from that.

Implement the InputProcessor interface in your class then set the input processor to your class

Gdx.input.setInputProcessor(this);

And override the keyDown method

@Override
public boolean keyDown(InputEvent event, int keycode) {
    typeArea.append(Keys.toString(keycode));
    return super.keyDown(event, keycode);
}

Upvotes: 1

Related Questions