如何在Java/Swing中实现Ctrl + Z/Command + Z? [英] How do I implement Ctrl+Z / Command+Z in Java/Swing?

查看:88
本文介绍了如何在Java/Swing中实现Ctrl + Z/Command + Z?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究一个需要撤消/重做功能的Java小程序.这是设置热键的代码(在Windows上很好用).

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

我的问题是:如何在Mac上使用Command + Z?我应该只检查System.getProperty("os.name")还是有一个更优雅的选择??

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);
    }
}

谢谢

尼尔

推荐答案

没关系,我在这里找到它

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

这篇关于如何在Java/Swing中实现Ctrl + Z/Command + Z?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆