Search code examples
javaswinghotkeys

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


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


Solution

  • Ah nevermind, I found it here

    This should undo on any platform.

    KeyStroke.getKeyStroke(KeyEvent.VK_Z, Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx());
    

    Parsing it through setAccelerator() would set CTRL + Z as its shortcut.
    (Most swing components have this method.)