Skip to content

How to change the action performed by KeyListener during a specific event

I’m trying to make a simple RPG game using Java Swing. The game is controlled by keyboard using Key Listener. The issue is that I need the “key bindings” to change during a specific event, for example during a dialogue between player and NPC. Let’s say the game gives me 3 dialogue choices. To choose one of them I need to press 1, 2 or 3 on my keyboard. Then after choosing one of them the dialogue continues and then the game gives me another 4 choices. Now I would like to be able to use 1, 2, 3 and 4 again but they are already used and I don’t know how to rebind them.


There are two different approaches to this. First, you could use an API such as the the Key Bindings API. Key bindings allow you to have it activate on focus, not on the component. This post should perfectly answer your problem.

Just for a quick reference, here is how to bind a single key with the API:

myComponent.getInputMap().put("userInput", "myAction");
myComponent.getActionMap().put("myAction", action);

The second approach involves extending the AbstractAction class. An example would be:

public class DownAction extends AbtractAction {
    public void actionPerformed(ActionEvent e) {
    //code here

This video shows step by step how to do this