Escape Key and Dialog
Posted by Rob Camick on October 17, 2010
In some applications that use dialogs the Escape key can be used to close the dialog. This feature is not support in the base JDK but can easily be added.
Like many Swing features, this support can be added by using Key Bindings. In this case, as discussed in my blog article on Key Bindings, you would add a key binding to the JRootPane of the dialog. The Action for the Escape key would simply dispose the current window that has focus. This approach is easy to implement and works well. Unfortunately it works too well. In some cases the dialog will close when you don’t want it to.
For example, when you have a JPopupMenu displayed on the dialog, the Escape key should close the popup menu first. Then the second time you use the Escape key the dialog should be closed. Therefore, our custom Action needs to have a little smarts built into it.
Upon trying to understand a little better how a JPopupMenu works I made the follow observations:
- the JRootPane has focus when a popup menu is visible
- the “cancel” Action is used from the JRootPane ActionMap to hide popup menus
Using this information I was able to create a simple EscapeAction that is invoked when the Escape key is pressed. The EscapeAction will invoke the default Escape key Action when a popup menu is visible, otherwise it will simply dispose of the focused dialog. You must register each dialog with the EscapeAction. The basic code would be:
EscapeAction escapeAction = new EscapeAction();
Although the EscapeAction was written with the JDialog in mind, the functionality is actually added to the JRootPane so it will also work with a JWindow or JFrame.