Java JDialog Escape Key addEscapeListener(final JDialog dialog, final boolean hide)

Here you can find the source of addEscapeListener(final JDialog dialog, final boolean hide)

Description

Adds a listener to the dialog to close the dialog if the user presses the escape key.

License

Open Source License

Parameter

Parameter Description
dialog a parameter
hide If true, the dialog will be hidden rather than disposed of.

Declaration

public static void addEscapeListener(final JDialog dialog, final boolean hide) 

Method Source Code


//package com.java2s;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;

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

import javax.swing.KeyStroke;

public class Main {
    /**//w  ww .j  av  a  2  s.co  m
     * Adds a listener to the dialog to close the dialog if the user presses the
     * escape key.
     *
     * @param dialog
     * @param hide If true, the dialog will be hidden rather than disposed of.
     */
    public static void addEscapeListener(final JDialog dialog, final boolean hide) {
        ActionListener escListener = new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                if (hide) {
                    // Hide the dialog
                    dialog.setVisible(false);
                } else {
                    // Dispose of the dialog. 
                    dialog.dispose();
                }
            }
        };
        dialog.getRootPane().registerKeyboardAction(escListener, KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0),
                JComponent.WHEN_IN_FOCUSED_WINDOW);
    }
}

Related

  1. addEscapeKeyCloseAction(final JDialog dialog)
  2. addEscapeKeyCloseAction(final JDialog dialog)
  3. addEscapeListener(final JDialog dialog)
  4. addEscapeListener(final JDialog dialog)
  5. addEscapeListener(final JDialog dialog)
  6. addEscapeToCloseSupport(final JDialog dialog)
  7. addEscapeToCloseSupport(final JDialog dialog, final boolean fadeOnClose)
  8. addEscKeyAction(javax.swing.JDialog dialog, javax.swing.Action action)
  9. closeOnEsc(final JDialog dlg)