Java JDialog Escape Key closeOnEsc(JDialog dialog)

Here you can find the source of closeOnEsc(JDialog dialog)

Description

close On Esc

License

Open Source License

Declaration

public static void closeOnEsc(JDialog dialog) 

Method Source Code


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

import java.awt.*;
import java.awt.event.*;

import javax.swing.*;

public class Main {
    private static final KeyStroke ESC = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0, false);
    private static final Action CLOSE_ACTION = new AbstractAction() {
        public void actionPerformed(ActionEvent e) {
            Window window = SwingUtilities.getWindowAncestor((Component) e.getSource());
            // Dispatch an event so it's as if the window's close button was clicked.
            // The client has to set up the right behavior for that case.
            window.dispatchEvent(new WindowEvent(window, WindowEvent.WINDOW_CLOSING));
        }/* ww  w.  j  av  a 2s  . c o m*/
    };

    public static void closeOnEsc(JDialog dialog) {
        closeOnKeyStroke(dialog.getRootPane(), ESC);
    }

    public static void closeOnEsc(JFrame frame) {
        closeOnKeyStroke(frame.getRootPane(), ESC);
    }

    public static void closeOnKeyStroke(JFrame frame, KeyStroke keyStroke) {
        closeOnKeyStroke(frame.getRootPane(), keyStroke);
    }

    private static void closeOnKeyStroke(JRootPane rootPane, KeyStroke keyStroke) {
        final String CLOSE_ACTION_NAME = "e.gui.JFrameUtilities.CloseFrameOnKeyStroke";
        rootPane.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(keyStroke, CLOSE_ACTION_NAME);
        rootPane.getActionMap().put(CLOSE_ACTION_NAME, CLOSE_ACTION);
    }
}

Related

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