0
votes

I have implemented a JDialog and have added a checkbox apart from ok and cancel button. I have put cancel as default button and when dialog comes up, cancel is selected default and on pressing enter key, cancel operation is executed.

By pressing tab, when I reach to checkbox and press enter, it does not select the checkbox. But, on pressing space key, it gets selected.

However, switching between ok and cancel button using tab and then pressing enter, does respective actions.

Please suggest what should be done such that checkbox gets selected on pressing enter.

1
do you have a Key Listener that if the check box is in focus or something like that it selects it? - 3kings
As far as i remember "enter" does normally not select a checkbox. The space-key herefore is used. Otherwise you can add a KeyListener to the ckeckbox. - Denis Lukenich
Don't use a KeyLIstener. Swing was designed to be used with Key Bindings. - camickr

1 Answers

1
votes

Each LAF has a default key that is used to select the check box.

Check out Key Bindings which will show the default bindings for a check box in your LAF.

If you want to add the same functionality for another key, then you need to manage the Key Bindings. So to handle the Enter key you should use:

InputMap im = checkB.getInputMap();
KeyStroke existingKeyStroke = KeyStroke.getKeyStroke("SPACE");
KeyStroke addedKeyStroke = KeyStroke.getKeyStroke("ENTER");
im.put(addedKeyStroke, im.get(existingKeyStroke));
existingKeyStroke = KeyStroke.getKeyStroke("released SPACE");
addedKeyStroke = KeyStroke.getKeyStroke("released ENTER");
im.put(addedKeyStroke, im.get(existingKeyStroke));

The above code will support the Enter key on a single component. If you want the Enter key support on all check boxes in your application then you would use:

InputMap im = (InputMap)UIManager.get("CheckBox.focusInputMap");