2

What is the best way to define the actions for lots of key mappings for a component in Swing?

I built my own Text View in Swing and want to define actions for a lot of keys. The way I'm currently doing it (for around 10 keys so far) is:

ActionMap actionMap = DBDocument.this.getActionMap();
int condition = JComponent.WHEN_FOCUSED;
InputMap inputMap = DBDocument.this.getInputMap(condition);
String tab = "tab";
actionMap.put(tab, new AbstractAction() {
            private static final long   serialVersionUID    = 1L;
            @Override
             public void actionPerformed(ActionEvent ap) {
                if(mDocumentModel != null){
                    //Do some stuff here
                }
             }
          });

This is obviously a very verbose way of defining key bindings. Ideally I would be able to define an action that deals with lots of possibilities (e.g. [A-Z] or [0-9]). I've searched for definitions in the OpenJDK but didn't get very far.

mKorbel
  • 109,525
  • 20
  • 134
  • 319
alistair
  • 1,164
  • 10
  • 27
  • 1
    put all ["LOTS of Key mappings" to array](http://stackoverflow.com/a/7940227/714968), use one array for plain keys [A-Z]/[0-9], second for modifier + key (e.g. ALT + [A-Z]/[0-9]), etc – mKorbel Aug 14 '13 at 11:10
  • and to use is/setEnabled for your XxxAction – mKorbel Aug 14 '13 at 11:12

1 Answers1

1

Kudos for avoiding repetition by applying the DRY principle. Several examples of DRY actions are cited here, but the common thread is actions that share a common model, such as Document, or are shared by a group of related buttons.

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