The best way I can see is to add an Action
to the action map of the root pane, and link that action to the escape key using the root pane's input map.
For this, you need an Action
. If your cancel button's behaviour is implemented as an action (ie. cancelButton.getAction() != null
), then this will work:
getRootPane().getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), "CANCEL");
getRootPane().getActionMap().put("CANCEL", cancelButton.getAction());
Otherwise, if the cancel button's logic is implemented via an ActionListener
, you could have the actionPerformed()
method of the ActionListener
call a private void onCancel()
method that implements the logic, and register a "cancel" action that calls the same method.
getRootPane().getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), "CANCEL");
getRootPane().getActionMap().put("CANCEL", new AbstractAction(){
@Override
public void actionPerformed(ActionEvent e)
{
onCancel();
}
});