Java: Close a JFrame with Escape
Comments available as RSS 2.0
This will close a JFrame when the escape key is pressed. The actionPerformed method can do be used to call another method or to close the frame which called it.
KeyStroke escapeKeyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0, false); Action escapeAction = new AbstractAction() { // close the frame when the user presses escape public void actionPerformed(ActionEvent e) { myFrame.dispose(); } }; myFrame.getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(escapeKeyStroke, "ESCAPE"); myFrame.getRootPane().getActionMap().put("ESCAPE", escapeAction);







Comments
Leave a Comment