简体   繁体   中英

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?

您是否尝试使用:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM