javaswingjmenuitemacceleratorkey

JMenuCheckBox: How to set an accelerator with only 1 key


I have a JMenuCheckBox that toggles the sound in my program on and off. I set an accelerator using:

toggleSoundMenuCheckBox.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, ActionEvent.ALT_MASK));

This toggles the check box by pressing ALT + S.

Is there any way to use an accelerator using only a single key (I would like it to toggle on/off using just the 'S' key without pressing ALT or any other key).


Solution

  • You can use the overloaded getKeyStroke(char) for that. Example:

    KeyStroke.getKeyStroke('s')
    

    This will give you a keystroke with only the key and no modifier keys.

    Beware: When binding single keys like this, then you may not be able to type it in a text box.