Force the escape key to call the same action as pressing the JDialog Cancel button. - Java Swing

Java examples for Swing:JOptionPane

Description

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

Demo Code


//package com.java2s;

import java.awt.event.ActionEvent;

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 {
    /**//from   ww  w . j av a  2 s .c om
     * Force the escape key to call the same action as pressing the Cancel button.
     *
     * <P>This does not always work. See class comment.
     */
    private static void addCancelByEscapeKey(final JDialog fDialog) {
        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);
        AbstractAction cancelAction = new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent e) {
                closeDialog(fDialog);
            }
        };
        fDialog.getRootPane().getActionMap()
                .put(CANCEL_ACTION_KEY, cancelAction);
    }

    private static void closeDialog(JDialog fDialog) {
        fDialog.dispose();
    }
}

Related Tutorials