Search code examples
javaswingkey-bindings

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

I'm sure I'm missing something obvious. What is it?


Solution

  • did you try using:

    KeyStroke.getKeyStroke(KeyEvent.VK_S, InputEvent.CTRL_MASK);