Here you can find the source of setEscapeKeyboardAction(final Window window, JComponent pane)
Parameter | Description |
---|---|
window | a parameter |
pane | a parameter |
public static void setEscapeKeyboardAction(final Window window, JComponent pane)
//package com.java2s; /*/* w w w. j a v a 2s . c om*/ * Jajuk * Copyright (C) The Jajuk Team * http://jajuk.info * * 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 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, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * */ import java.awt.KeyEventDispatcher; import java.awt.KeyboardFocusManager; import java.awt.Window; import java.awt.event.KeyEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import javax.swing.JComponent; public class Main { /** * Registers the ESCAPE key on the Panel so that it closes the Dialog. * * @param window * @param pane */ public static void setEscapeKeyboardAction(final Window window, JComponent pane) { final KeyEventDispatcher dispatcher = new KeyEventDispatcher() { @Override public boolean dispatchKeyEvent(KeyEvent e) { // For some reasons (under Linux at least), pressing escape only trigger PRESSED // and RELEASED key events if (e.getKeyCode() == KeyEvent.VK_ESCAPE && e.getID() == KeyEvent.KEY_PRESSED && window.isFocused()) { window.dispose(); return true; } return false; } }; // Add keystroke to close window when pressing escape KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(dispatcher); // make sure the key event dispatcher is removed as soon as the Window is closing window.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { KeyboardFocusManager.getCurrentKeyboardFocusManager().removeKeyEventDispatcher(dispatcher); } @Override public void windowClosed(WindowEvent e) { KeyboardFocusManager.getCurrentKeyboardFocusManager().removeKeyEventDispatcher(dispatcher); } }); } }