如何在 Java/Swing 中实现 Ctrl+Z / Command+Z?
我正在开发一个需要撤消/重做功能的 Java 小程序。下面是设置热键的代码(在 Windows 上效果很好)。
我的问题是:如何让它在 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);
}
}
谢谢,
尼尔
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
啊没关系,我找到了它 此处
这应该在任何平台上撤消。
通过
setAccelerator()
解析它会将 CTRL + Z 设置为其快捷方式。(大多数 Swing 组件都有这种方法。)
Ah nevermind, I found it here
This should undo on any platform.
Parsing it through
setAccelerator()
would set CTRL + Z as its shortcut.(Most swing components have this method.)