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.requestFocusInWindow();
getRootPane().setDefaultButton(buttonCancel);

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

 
contentPane.registerKeyboardAction(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        onCancel();
    }
}, 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.

dialog.jpg



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

Please sign in to leave a comment.