Java JFrame closeOnEsc(JFrame frame)

Here you can find the source of closeOnEsc(JFrame frame)

Description

close On Esc

License

Open Source License

Declaration

public static void closeOnEsc(JFrame frame) 

Method Source Code

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

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;

import java.awt.event.KeyEvent;
import java.awt.event.WindowEvent;

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));
        }/*from  ww  w .j av a  2  s .  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 = "com.jakeapp.gui.swing.helpers.GuiUtilities.CloseFrameOnKeyStroke";
        rootPane.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(keyStroke, CLOSE_ACTION_NAME);
        rootPane.getActionMap().put(CLOSE_ACTION_NAME, CLOSE_ACTION);
    }
}

Related

  1. centreWindow(Window c, JFrame frame)
  2. changeLookAndFeel(final String lookName, final JFrame frame)
  3. chooseFile(String directoryPath, String dialogTitle, String selectedFileName, boolean saveDialog, String[] extensions, JFrame parentFrame)
  4. ChooserDemo(JFrame jf, Component comp)
  5. closeFrame(JFrame frame, JProgressBar progressBar)
  6. closeOnEscape(final JFrame frame)
  7. closeOnEscape(final JFrame frame)
  8. closeOnKeyStroke(JFrame frame, KeyStroke keyStroke)
  9. closeWindow(final JFrame frame)