Registers a keystroke to close the given dialog. - Java Swing

Java examples for Swing:JOptionPane

Description

Registers a keystroke to close the given dialog.

Demo Code

/**//w  w w .j  a v  a 2 s .  c  om
 * (c) 2000-2011 Carlos G?mez Rodr?guez, todos los derechos reservados / all rights reserved.
 * Licencia en license.txt / License in license.txt
 * File created: 26/10/2012 17:14:36
 */
//package com.java2s;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.KeyStroke;

public class Main {
    /**
     * Registers a keystroke to close the given dialog.
     * @param dialog
     * @param keyStroke
     */
    public static void registerCloseAction(final JDialog dialog,
            KeyStroke keyStroke) {
        ActionListener escListener = new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                dialog.dispose();
            }
        };

        dialog.getRootPane().registerKeyboardAction(escListener, keyStroke,
                JComponent.WHEN_IN_FOCUSED_WINDOW);
    }

    /**
     * Registers a keystroke to close the given dialog.
     * @param dialog
     * @param keyStroke
     */
    public static void registerCloseAction(final JFrame dialog,
            KeyStroke keyStroke) {
        ActionListener escListener = new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                dialog.dispose();
            }
        };

        dialog.getRootPane().registerKeyboardAction(escListener, keyStroke,
                JComponent.WHEN_IN_FOCUSED_WINDOW);
    }
}

Related Tutorials