Java tutorial
//package com.java2s; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import javax.swing.JComponent; import javax.swing.JDialog; import javax.swing.KeyStroke; public class Main { /** * Sets the given action so it's invoked if the user hits the escape key. * @param dialog The dialog to attach the escape key. * @param abortAction The action that is invoked if the escape key is pressed. */ public static void setEscapeWindowAction(JDialog dialog, ActionListener abortAction) { if (abortAction != null) { ((JComponent) dialog.getContentPane()).registerKeyboardAction(abortAction, KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), JComponent.WHEN_IN_FOCUSED_WINDOW); } } }