Question

For a Text-Editor I'm developing I have overriden the default Action to the HOME-key. However in some cases I would still like to make use of the original HOME action (to jump to the beginning of the line). How can I fire this original action?

Example-code:

//Add the homekey and its action to the text-editor:
Key homeKey = KeyStroke.getKeyStroke("HOME");
editor.getInputMap().put(homeKey, new HomeCommand()); 
...

private class HomeCommand extends AbstractAction {

    @Override
    public void actionPerformed(ActionEvent ev) {
        if(doSomethingSpecial())
            performSpecialHomeAction();
        else
            performRegularHomeAction(); //How to get the regular action??
    }
}

Note: I'm looking for the elegant solution, I'd prefer not to write my own version of the HomeKey-Action.

I have googled and tried several approaches, none of them worked:

  • Action a = area.getActionMap().get(KeyStroke.getKeyStroke("HOME")); Resulted in null.
  • Simulate pressing the Home Key via the Robot class. That however just fires my own custom Action.
Was it helpful?

Solution

You can have a reference in your HomeCommand.

class HomeCommand extends AbstractAction {

 private final Action action;

    public HomeCommand(Action action){
         this.action=action;
    }

    @Override
    public void actionPerformed(ActionEvent ev) {
        if(doSomethingSpecial())
            performSpecialHomeAction();
        else
            action.actionPerformed(ev); 
    }
}

Then when you create it.

KeyStroke homeKey = KeyStroke.getKeyStroke("HOME");
InputMap inputMap = editor.getInputMap(JComponent.WHEN_FOCUSED);
ActionMap actionMap = editor.getActionMap();
Action action = actionMap.get("caret-begin-line");
inputMap.put(homeKey, "caret-begin-line"); 
actionMap.put("caret-begin-line", new HomeCommand(action));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top