Java JDialog Escape Key closeOnEscapePressed(final JDialog dialog)

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

Description

Registers an Action on the dialog on the Esc key that disposes the dialog.

License

Open Source License

Parameter

Parameter Description
dialog a parameter

Declaration

public static void closeOnEscapePressed(final JDialog dialog) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

import java.awt.event.ActionEvent;

import java.awt.event.KeyEvent;

import javax.swing.AbstractAction;
import javax.swing.ActionMap;

import javax.swing.InputMap;

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

import javax.swing.JRootPane;

import javax.swing.KeyStroke;

public class Main {
    /**/*from   w  w  w . j a v  a2s .c  o  m*/
     * Registers an Action on the dialog on the Esc key that disposes the dialog.
     * 
     * @param dialog
     */
    public static void closeOnEscapePressed(final JDialog dialog) {
        JRootPane rootPane = dialog.getRootPane();
        InputMap im = rootPane.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
        ActionMap actionMap = rootPane.getActionMap();
        KeyStroke ks = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0);

        im.put(ks, "UiUtilsEscape");
        actionMap.put("UiUtilsEscape", new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent e) {
                dialog.dispose();
            }
        });
    }
}

Related

  1. addEscapeToCloseSupport(final JDialog dialog, final boolean fadeOnClose)
  2. addEscKeyAction(javax.swing.JDialog dialog, javax.swing.Action action)
  3. closeOnEsc(final JDialog dlg)
  4. closeOnEsc(JDialog dialog)
  5. closeOnEscape(final JDialog dialog)
  6. decorate(final JDialog d, boolean closeOnEscape)
  7. enableCloseByEscape(final JDialog dialog)
  8. installEscapeCloseOperation(final JDialog dialog)
  9. installEscapeCloseOperation(final JDialog dialog)