Java JDialog Escape Key addCancelByEscapeKey(JDialog fDialog, AbstractAction cancelAction)

Here you can find the source of addCancelByEscapeKey(JDialog fDialog, AbstractAction cancelAction)

Description

Force the escape key to call the same action as pressing the Cancel button.

License

BSD License

Declaration

public static void addCancelByEscapeKey(JDialog fDialog, AbstractAction cancelAction) 

Method Source Code

//package com.java2s;
/**/*from  w  ww.  j a  v  a2s.  co m*/
 * some swing helpers from
 * http://www.javapractices.com/topic/TopicAction.do?Id=152
 * 
 * @author Hirondelle Systems (code snippets used on BSD license)
 */

import java.awt.event.KeyEvent;

import javax.swing.AbstractAction;

import javax.swing.InputMap;
import javax.swing.JComponent;
import javax.swing.JDialog;

import javax.swing.KeyStroke;

public class Main {
    /**
     * Force the escape key to call the same action as pressing the Cancel
     * button.
     * 
     * <P>
     * The <tt>Escape</tt> key does not always work (for example, when a
     * <tt>JTable</tt> row has the focus)
     */
    public static void addCancelByEscapeKey(JDialog fDialog, AbstractAction cancelAction) {
        String CANCEL_ACTION_KEY = "CANCEL_ACTION_KEY";
        int noModifiers = 0;
        KeyStroke escapeKey = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, noModifiers, false);
        InputMap inputMap = fDialog.getRootPane().getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
        inputMap.put(escapeKey, CANCEL_ACTION_KEY);
        fDialog.getRootPane().getActionMap().put(CANCEL_ACTION_KEY, cancelAction);
    }
}

Related

  1. actionOnEsc(final JDialog dialog, final Action action)
  2. addCancelEscape(JDialog f, AbstractAction cancelAction)
  3. addDisposeActionWithEscapeKey(final JDialog dialog)
  4. addDisposeOnAction(AbstractButton which, final JDialog dia)
  5. addDisposeOnEscape(final JDialog dia)