Pressing enter does not select checkbox

I am working on a plugin and have implemeted a dialog box which has "Ok" and "Cancel" button and a checkbox. I have set default button as "Cancel" and have registered "enter" key action to execute cancel operation like below:


buttonCancel.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {

contentPane.registerKeyboardAction(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
}, KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), JComponent.WHEN_FOCUSED);

Now, when I press tab button, when focus moves to checkbox, and then on pressing enter key, cancel operation is executed. Below is the screenshot, where focus is on both checkbox and cancel and cancel operation is executed.


On pressing space key, checkbox gets selected. I have used below from internet, but it does not help.

private static void setupEnterActionForAllButtons() {
    InputMap im = (InputMap) UIManager.getDefaults().get("Button.focusInputMap");
    Object pressedAction = im.get(KeyStroke.getKeyStroke("pressed SPACE"));
    Object releasedAction = im.get(KeyStroke.getKeyStroke("released SPACE"));

    im.put(KeyStroke.getKeyStroke("pressed ENTER"), pressedAction);
    im.put(KeyStroke.getKeyStroke("released ENTER"), releasedAction);

Please suggest what do I need to do such that at above position, on pressing enter checkbox gets selected.

1 comment
Comment actions Permalink

I tried below for checkbox and it worked

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

Please sign in to leave a comment.