The source of much user frustration with Swing is when windows and dialogs don't act in the way that they expect.
Generally, a user expects to be able to press the Escape key to close a dialog window (in Windows).
By default Swing JDialogs don't provide this behavior. However, this can easily be implemented by creating a simple
subclass of the JDialog class. The code below will equip any subclass with this "close on escape" functionality.
public abstract class EscapableDialog extends JDialog {
protected JRootPane createRootPane() {
Action action = new AbstractAction() {
public void actionPerformed(ActionEvent arg0) {
hide();
}
};
KeyStroke stroke = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0);
JRootPane rootPane = new JRootPane();
rootPane.getActionMap().put(action,action);
rootPane.getInputMap(JComponent.WHEN_FOCUSED).put(stroke, action);
return rootPane;
}
public EscapableDialog() throws HeadlessException {
super();
}
public EscapableDialog(Dialog arg0) throws HeadlessException {
super(arg0);
}
public EscapableDialog(Dialog arg0, boolean arg1) throws HeadlessException {
super(arg0, arg1);
}
public EscapableDialog(Dialog arg0, String arg1) throws HeadlessException {
super(arg0, arg1);
}
public EscapableDialog(Dialog arg0, String arg1, boolean arg2)
throws HeadlessException {
super(arg0, arg1, arg2);
}
public EscapableDialog(Dialog arg0, String arg1, boolean arg2,
GraphicsConfiguration arg3) throws HeadlessException {
super(arg0, arg1, arg2, arg3);
}
public EscapableDialog(Frame arg0) throws HeadlessException {
super(arg0);
}
public EscapableDialog(Frame arg0, boolean arg1) throws HeadlessException {
super(arg0, arg1);
}
public EscapableDialog(Frame arg0, String arg1) throws HeadlessException {
super(arg0, arg1);
}
public EscapableDialog(Frame arg0, String arg1, boolean arg2)
throws HeadlessException {
super(arg0, arg1, arg2);
}
public EscapableDialog(Frame arg0, String arg1, boolean arg2,
GraphicsConfiguration arg3) {
super(arg0, arg1, arg2, arg3);
}
Read: Closing Swing Windows with the Escape Key