[英]Why is this Java Swing key binding not working?
I've read through the Java tutorial on key bindings as well as half a dozen posts on this site with examples. 我已经阅读了有关键绑定的Java教程,并阅读了该站点上的六个示例示例。 I can't for the life of me figure out why the following snippet is not working as expected: 我一辈子都无法弄清楚为什么以下代码段无法按预期工作:
String ctrlSave = "CTRL Save";
myPanel.getInputMap().put(KeyStroke.getKeyStroke('s', InputEvent.CTRL_DOWN_MASK), ctrlSave);
myPanel.getActionMap().put(ctrlSave, new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
int returnVal = chooserFileSave.showSaveDialog(myPanel);
if (returnVal == JFileChooser.APPROVE_OPTION) {
fileSave = chooserFileSave.getSelectedFile();
myPanel.getActiveRoute().saveToGPXFile(fileSave);
}
}
});
If I replace this: 如果我替换此:
myPanel.getInputMap().put(KeyStroke.getKeyStroke('s', InputEvent.CTRL_DOWN_MASK), ctrlSave);
with this: 有了这个:
myPanel.getInputMap().put(KeyStroke.getKeyStroke('s'), ctrlSave);
Then it works fine (of course, it is then 's' I have to hit and not "ctrl+s" as I desired). 然后它就可以正常工作了(当然,那是我必须打的“ s”,而不是我想要的“ ctrl + s”)。
I'm sure I'm missing something obvious. 我确定我缺少明显的东西。 What is it? 它是什么?
您是否尝试使用:
KeyStroke.getKeyStroke(KeyEvent.VK_S, InputEvent.CTRL_MASK);
Your key binding is set to only when the component is selected. 仅当选择组件时,您的按键绑定才会设置为。 You need to change your input map to: 您需要将输入映射更改为:
myPanel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke('s', InputEvent.CTRL_DOWN_MASK), ctrlSave);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.