【问题标题】:Java: Call original key action after overrideJava:覆盖后调用原始键操作
【发布时间】:2014-01-01 20:39:13
【问题描述】:

对于我正在开发的文本编辑器,我已将默认操作覆盖为 HOME 键。但是在某些情况下,我仍然想使用原始的 HOME 动作(跳转到行首)。我怎样才能触发这个原始动作?

示例代码:

//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 版本。

我用谷歌搜索并尝试了几种方法,但都没有奏效:

  • 动作 a = area.getActionMap().get(KeyStroke.getKeyStroke("HOME")); 结果为空。
  • 通过 Robot 类模拟按下 Home 键。然而,这只会触发我自己的自定义动作。

【问题讨论】:

  • 你试过 super.performRegularHomeAction(); ?
  • @MadProgrammer 该函数不存在。如果您查看代码,您会看到我正在替换普通的 HomeAction-Class
  • 为什么在放HomeCommand 之前没有一个regularHomeAction 的引用?
  • 我怎样才能得到它?如下:Action a = area.getActionMap().get(KeyStroke.getKeyStroke("HOME"));结果为空。
  • @MadProgrammer 是这个related

标签: java swing action key-bindings keyevent


【解决方案1】:

您可以在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));

【讨论】:

  • 这将是完美的,但是:Action action = actionMap.get(inputMap.get(homeKey));返回空值。
  • 那么您没有与“HOME”相关联的操作
  • 没错,我不知道。我想要正常按 HOME 时会发生的常规动作,即跳到行首。
  • 太棒了!谢谢!
猜你喜欢
  • 2013-06-01
  • 2021-04-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多