Feb
8
2008

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);
Like this post? Tell someone!
  • Digg
  • StumbleUpon
  • del.icio.us
  • Facebook
  • Google
  • Technorati

Comments

Leave a Comment

Login using OpenID or enter your details below to leave a comment.

OpenID
Anonymous


Comment