Decorates the given dialog with a keyboard action which calls JDialog#dispose() when the ESC key is hit while the dialog or one of its subcomponents has the focus. - Java Swing

Java examples for Swing:JDialog

Description

Decorates the given dialog with a keyboard action which calls JDialog#dispose() when the ESC key is hit while the dialog or one of its subcomponents has the focus.

Demo Code


//package com.java2s;

import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import javax.swing.AbstractAction;

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

import javax.swing.KeyStroke;

public class Main {
    /**/*from w  w  w .  j  av a2 s.  c o m*/
     * Decorates the given dialog with a keyboard action which calls
     * {@link JDialog#dispose() } when the ESC key is hit while the dialog or one
     * of its subcomponents has the focus.
     * 
     * @param dialog
     *            the dialog to decorate.
     */
    public static void decorateWithDisposeOnESC(final JDialog dialog) {
        dialog.getRootPane().registerKeyboardAction(
                new AbstractAction() {

                    private static final long serialVersionUID = 4054546658098440109L;

                    @Override
                    public void actionPerformed(ActionEvent e) {
                        dialog.dispose();
                    }
                }, KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0),
                JComponent.WHEN_IN_FOCUSED_WINDOW);
    }
}

Related Tutorials