Java Swing Key Action addCloseActionWithEscapeKey(final Window window, JRootPane rootPane)

Here you can find the source of addCloseActionWithEscapeKey(final Window window, JRootPane rootPane)

Description

Adds the close action with escape key.

License

Open Source License

Parameter

Parameter Description
window the window
rootPane the root pane

Declaration

public static void addCloseActionWithEscapeKey(final Window window, JRootPane rootPane) 

Method Source Code

//package com.java2s;
/*//from  w  w w  . j  a va2 s  .com
 * aTunes 1.14.0
 * Copyright (C) 2006-2009 Alex Aranda, Sylvain Gaudard, Thomas Beckers and contributors
 *
 * See http://www.atunes.org/wiki/index.php?title=Contributing for information about contributors
 *
 * http://www.atunes.org
 * http://sourceforge.net/projects/atunes
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 */

import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;

import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JComponent;
import javax.swing.JRootPane;

import javax.swing.KeyStroke;

public class Main {
    /**
     * Adds the close action with escape key.
     * 
     * @param window
     *            the window
     * @param rootPane
     *            the root pane
     * 
     */
    public static void addCloseActionWithEscapeKey(final Window window, JRootPane rootPane) {
        // Handle escape key to close the window

        KeyStroke escape = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0, false);
        Action escapeAction = new AbstractAction() {
            private static final long serialVersionUID = 0L;

            @Override
            public void actionPerformed(ActionEvent e) {
                window.setVisible(false);
            }
        };
        rootPane.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(escape, "ESCAPE");
        rootPane.getActionMap().put("ESCAPE", escapeAction);
    }
}

Related

  1. addActionsToMap(Action[] list1, Map h)
  2. addCtrlEnterAction(JComponent comp, AbstractAction action)
  3. addEnterKey(JComponent control)
  4. addEscKeyAction(javax.swing.JComponent component, javax.swing.InputMap inputMap, javax.swing.Action action)
  5. addHotKey(int key, JComponent to, String actionName, Action action)