Java Window enableCloseWindowWithEscape(final W window)

Here you can find the source of enableCloseWindowWithEscape(final W window)

Description

Configures the given window to be closed when the Escape button is pressed.

License

Open Source License

Parameter

Parameter Description
W A window (JFrame, JDialog, etc.).
window Window to configure.

Declaration

public static <W extends Window & RootPaneContainer> void enableCloseWindowWithEscape(final W window) 

Method Source Code

//package com.java2s;
/*/* ww w .j  ava  2  s . c om*/
DrMIPS - Educational MIPS simulator
Copyright (C) 2013-2015 Bruno Nova <brunomb.nova@gmail.com>
    
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 3 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.
    
You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

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

import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JComponent;
import javax.swing.KeyStroke;
import javax.swing.RootPaneContainer;

public class Main {
    /**
     * Configures the given window to be closed when the Escape button is pressed.
     * @param <W> A window (JFrame, JDialog, etc.).
     * @param window Window to configure.
     */
    public static <W extends Window & RootPaneContainer> void enableCloseWindowWithEscape(final W window) {
        Action closeAction = new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent e) {
                window.dispatchEvent(new WindowEvent(window, WindowEvent.WINDOW_CLOSING));
            }
        };

        window.getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW)
                .put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), "close");
        window.getRootPane().getActionMap().put("close", closeAction);
    }
}

Related

  1. cascade(Window[] windows, Rectangle dBounds, int separation)
  2. closeByESC(final Window window, JPanel panel)
  3. createWindow(String name, int width, int height, boolean guiOn)
  4. decorate(final Window w)
  5. dock(Window window, Window dockTo)
  6. fadeOut(final Window window, final boolean dispose)
  7. flashMessage(final Window parent, String string)
  8. getVisibleWindowByName(String name)
  9. getWindow(final Object source)