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

时间:2010-12-16 22:13:02

标签: java swing hotkeys

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

我的问题是:如何在mac上使用命令+ 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);
    }
}

谢谢,

尼尔

1 个答案:

答案 0 :(得分:9)

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

找到了

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

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