Here you can find the source of addEscapeKeyCloseAction(final JDialog dialog)
public static void addEscapeKeyCloseAction(final JDialog dialog)
//package com.java2s; //License from project: Open Source License import java.awt.event.*; import javax.swing.*; public class Main { /**/*from w w w . j a v a 2s .co m*/ * Adds a key listener to a given {@link JDialog} that diposes it when the escape * key is pressed. */ public static void addEscapeKeyCloseAction(final JDialog dialog) { dialog.getRootPane().registerKeyboardAction(new ActionListener() { public void actionPerformed(ActionEvent e) { dialog.dispose(); } }, KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), JComponent.WHEN_IN_FOCUSED_WINDOW); } /** * Schedule disposal of a frame (async). */ public static void dispose(final JFrame frame) { SwingUtilities.invokeLater(new Runnable() { public void run() { if (frame.isDisplayable()) frame.dispose(); } }); } }