Java tutorial
//package com.java2s; //License from project: Apache License import java.awt.event.ActionEvent; import javax.swing.*; public class Main { public static void closeOnEscape(final JFrame frame) { KeyStroke stroke = KeyStroke.getKeyStroke("ESCAPE"); Action actionListener = new AbstractAction() { public void actionPerformed(ActionEvent actionEvent) { frame.setVisible(false); frame.dispose(); } }; JRootPane rootPane = frame.getRootPane(); InputMap inputMap = rootPane.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW); inputMap.put(stroke, "ESCAPE"); rootPane.getActionMap().put("ESCAPE", actionListener); } }