如何在 Java/Swing 中实现 Ctrl+Z/Command+Z?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4465869/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 06:30:57  来源:igfitidea点击:

How do I implement Ctrl+Z / Command+Z in Java/Swing?

javaswinghotkeys

提问by Neal Ehardt

I'm working on a little Java applet that needs undo/redo functionality. Here's code to set up the hotkeys (works great on Windows).

我正在开发一个需要撤消/重做功能的小 Java 小程序。这是设置热键的代码(在 Windows 上效果很好)。

My question is: how do I make it use command+Z on mac? Should I just check System.getProperty("os.name") or is there a more elegant alternative??

我的问题是:如何让它在 mac 上使用 command+Z?我应该检查 System.getProperty("os.name") 还是有更优雅的选择?

private void setupUndoHotkeys() {
    String UNDO = "Undo action key";
    String REDO = "Redo action key";
    Action undoAction = new AbstractAction() {
        public void actionPerformed(ActionEvent e) {
            undo();
        }
    };
    Action redoAction = new AbstractAction() {
        public void actionPerformed(ActionEvent e) {
            redo();
        }
    };

    getActionMap().put(UNDO, undoAction);
    getActionMap().put(REDO, redoAction);

    InputMap[] inputMaps = new InputMap[] {
        getInputMap(JComponent.WHEN_FOCUSED),
        getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT),
        getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW),
    };
    for(InputMap i : inputMaps) {
        i.put(KeyStroke.getKeyStroke("control Z"), UNDO);
        i.put(KeyStroke.getKeyStroke("control Y"), REDO);
    }
}

Thanks,

谢谢,

Neal

尼尔

回答by Neal Ehardt

Ah nevermind, I found it here http://www.devdaily.com/blog/post/jfc-swing/how-program-apple-command-key-keystroke-java-swing-mac-osx

啊没关系,我在这里找到它http://www.devdaily.com/blog/post/jfc-swing/how-program-apple-command-key-keystroke-java-swing-mac-osx

This should be undo on any platform.

这应该在任何平台上撤消。

KeyStroke.getKeyStroke(KeyEvent.VK_Z, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())