对于我正在开发的文本编辑器,我已将默认操作覆盖为 HOME 键。然而,在某些情况下,我仍然想使用原来的 HOME 操作(跳转到行的开头)。我怎样才能触发这个原始 Action ?
示例代码:
//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??
}
}
注意:我正在寻找优雅的解决方案,我不想编写自己的 HomeKey-Action 版本。
我用谷歌搜索并尝试了几种方法,但没有一个有效:
- Action a = area.getActionMap().get(KeyStroke.getKeyStroke("HOME")); 结果为空。
- 通过 Robot 类模拟按下 Home 键。然而,这只会触发我自己的自定义操作。
最佳答案
您可以在 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);
}
}
然后当你创建它时。
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));
关于Java:覆盖后调用原始按键操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20873021/