1

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.

Nathan
  • 838
  • 5
  • 14
  • See also [`LinePanel`](http://stackoverflow.com/a/5797965/230513). – trashgod Jan 29 '13 at 18:05
  • After following the [*Key Bindings*](http://docs.oracle.com/javase/tutorial/uiswing/misc/keybinding.html) link from the answer that @trashgod linked to, it seems that Swing uses a very similar technique in regards to the original solution I suggested in my answer, that I wanted to improve. Since Swing uses this method, I am under the impression that it is likely the most straight forward way of tackling this. Guess that means, no, there really isn't much of a way to do this better. – Nathan Jan 29 '13 at 18:21
  • The example cited does not use `switch`. You may be able to parameterize or re-factor your `Action` implementation(s) to mitigate proliferation. – trashgod Jan 29 '13 at 18:26

1 Answers1

1

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.

Community
  • 1
  • 1
trashgod
  • 203,806
  • 29
  • 246
  • 1,045