Making Dialogs in Java Close When Escape is Pressed

In Windows and in OS X, if you press the escape key, dialogs close. It is equivalent to clicking on Cancel.

By default JDialogs in Java do not have this behaviour. If you want to add it to your JDialogs, you can use this subclass of JDialog. Instead of extending JDialog, extend EscapeKeyAwareDialog instead:

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.*;

public class EscapeKeyAwareDialog extends JDialog {

public EscapeKeyAwareDialog() throws HeadlessException {
super();
addCloseOnEscape(this);
}

public EscapeKeyAwareDialog(Dialog owner) throws HeadlessException {
super(owner);
addCloseOnEscape(this);
}

public EscapeKeyAwareDialog(Dialog owner, boolean modal) throws HeadlessException {
super(owner, modal);
addCloseOnEscape(this);
}

public EscapeKeyAwareDialog(Dialog owner, String title) throws HeadlessException {
super(owner, title);
addCloseOnEscape(this);
}

public EscapeKeyAwareDialog(Dialog owner, String title, boolean modal) throws HeadlessException {
super(owner, title, modal);
addCloseOnEscape(this);
}

public EscapeKeyAwareDialog(Dialog owner, String title, boolean modal, GraphicsConfiguration gc) throws HeadlessException {
super(owner, title, modal, gc);
addCloseOnEscape(this);
}

public EscapeKeyAwareDialog(Frame owner) throws HeadlessException {
super(owner);
addCloseOnEscape(this);
}

public EscapeKeyAwareDialog(Frame owner, boolean modal) throws HeadlessException {
super(owner, modal);
addCloseOnEscape(this);
}

public EscapeKeyAwareDialog(Frame owner, String title, boolean modal) throws HeadlessException {
super(owner, title, modal);
addCloseOnEscape(this);
}

public EscapeKeyAwareDialog(Frame owner, String title, boolean modal, GraphicsConfiguration gc) {
super(owner, title, modal, gc);
addCloseOnEscape(this);
}

public EscapeKeyAwareDialog(java.awt.Frame owner, String title) throws java.awt.HeadlessException {
super(owner, title);
addCloseOnEscape(this);
}

private void addCloseOnEscape(final JDialog dialog) {
ActionListener cancelListener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
setVisible(false);
}
};

KeyStroke stroke = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0);
JRootPane rootPane = dialog.getRootPane();
rootPane.registerKeyboardAction(cancelListener, stroke, JComponent.WHEN_IN_FOCUSED_WINDOW);
}
}