Java JDialog Key Event loadCommonKeyMap(final JDialog dialog)

Here you can find the source of loadCommonKeyMap(final JDialog dialog)

Description

This method enables exiting the dialog by pressing the escape key

License

Open Source License

Parameter

Parameter Description
dialog the JDialog

Declaration

public static void loadCommonKeyMap(final JDialog dialog) 

Method Source Code

//package com.java2s;
/* $Id$// w  ww  . ja v a  2s .  c  o m
 *****************************************************************************
 * Copyright (c) 2009 Contributors - see below
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *    linus
 *****************************************************************************
 *
 * Some portions of this file was previously release using the BSD License:
 */

import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import javax.swing.AbstractAction;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JRootPane;
import javax.swing.KeyStroke;

public class Main {
    /**
     * The key for the escape action
     */
    private static final String ACTION_KEY_ESCAPE = "escapeAction";

    /**
     * This method enables exiting the dialog by pressing the escape key
     * 
     * @param dialog    the JDialog
     */
    public static void loadCommonKeyMap(final JDialog dialog) {
        JRootPane rootPane = dialog.getRootPane();
        rootPane.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(
                KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0),
                ACTION_KEY_ESCAPE);
        // Add the action to the component
        rootPane.getActionMap().put(ACTION_KEY_ESCAPE,
                new AbstractAction() {
                    private static final long serialVersionUID = 0;

                    public void actionPerformed(ActionEvent evt) {
                        dialog.dispose();
                    }
                });
    }
}

Related

  1. installCloseKeyBinding(final JDialog dialog)
  2. installEnterKey(final JDialog comp, final Action action)
  3. registerCloseAction(final JDialog dialog, KeyStroke keyStroke)
  4. setupOKCancelHotkeys(JDialog dlg, JButton btnOK, final JButton btnCancel)