Search code examples
javaoopkey-bindings

Doing Different Actions Based On Customizable Keybindings


I need to take in customizable actions read from a file and bind them to a key for a program.

If I have a file like so:

w:up
s:down
a:left
d:right

How would I go about getting this running?

The only way I see it is doing this:

// hardcoded String to Action to turn "up" into an actual instruction
HashMap<String, Action> actions = new HashMap<String, Action();
actions.put("up", new Up());
actions.put("down", new Down()); // etc.


HashMap<Integer, Action> keybindings = new HashMap<Integer, Action>();
while (!endOfFile) {
    int key = letterToKeycode(getKey()); // gets keycode for letter
    Action action = actions.get(getCommand());
    keybindings.put(key, action);
    endOfFile = isEndOfFile();
}

Then when my keylistener method gets called, it does:

public void keyPressed(int keycode) {
    keybindings.get(keycode).doAction();
}

and doAction() would be in each Action class. So if I had Up(), it would call person.moveUp().

If I was to rebind most of my keys, it could result in hundreds of classes that are a few lines long.

There's something about the above concept, and a single switch statement that makes me want to avoid them. Is there "cleaner" trick to doing this?

As an example of what I mean, Eclipse has keybindings you can set in the preferences, so when you hit a key, it fires off an event and interprets what the key is supposed to do based on those settings. I'm attempting to do this.


Solution

  • Rather than create your own Map, use Key Bindings; LinePanel is an example. You may be able to parameterize or re-factor your Action implementation(s) to mitigate proliferation. To persist user-defined key assignments, you may be able to adapt the approach used in the example cited here.