Java tutorial
//package com.java2s; import java.awt.event.ActionEvent; import java.awt.event.KeyEvent; import javax.swing.AbstractAction; import javax.swing.ActionMap; import javax.swing.InputMap; import javax.swing.JComponent; import javax.swing.JDialog; import javax.swing.KeyStroke; public class Main { /** * Binds an action to the dialog so when the user presses the ESCAPE key, the dialog is hidden. * * @param dialog * the dialog to bind the action to. */ public static void bindEscapeAction(final JDialog dialog) { InputMap iMap = dialog.getRootPane().getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT); iMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), "escape"); ActionMap aMap = dialog.getRootPane().getActionMap(); aMap.put("escape", new AbstractAction() { public void actionPerformed(ActionEvent e) { dialog.setVisible(false); } }); } }