Java Swing KeyStroke closeOnKeyStroke(JRootPane rootPane, KeyStroke keyStroke)

Here you can find the source of closeOnKeyStroke(JRootPane rootPane, KeyStroke keyStroke)

Description

close On Key Stroke

License

Open Source License

Declaration

private static void closeOnKeyStroke(JRootPane rootPane, KeyStroke keyStroke) 

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.WindowEvent;

public class Main {
    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  .  java 2s .c om
    };

    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. bindAction(JComponent aComponent, String aCommand, Action anAction, KeyStroke aKeyStroke)
  2. bindKeyToAction(int keyCode, int modifiers, Action action, JComponent component, int condition)
  3. bindKeyToAction(JComponent c, KeyStroke key, Action a)
  4. clearActionBinding(final JComponent component, final KeyStroke keyStroke, final int condition)
  5. clearKeyStroke(JComponent component)
  6. componentListensForKey(JComponent component, int keyCode)
  7. configAction(Action action, String text, Icon icon, KeyStroke keyStroke)
  8. convertShortcutMask(KeyStroke ks, int shortcutMask)
  9. createItem(String name, Integer mnem, KeyStroke accel)