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

假如想象 提交于 2021-02-07 13:26:56

问题


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).

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??

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


回答1:


Ah nevermind, I found it here 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())


来源:https://stackoverflow.com/questions/4465869/how-do-i-implement-ctrlz-commandz-in-java-swing

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!