add JDialog Escape Listener - Java Swing

Java examples for Swing:JOptionPane

Description

add JDialog Escape Listener

Demo 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 {
    public static void addEscapeListener(final JDialog dialog) {
        ActionListener escListener = new ActionListener() {
            @Override//ww w . j av a  2 s .  co m
            public void actionPerformed(ActionEvent e) {
                dialog.setVisible(false);
            }
        };

        dialog.getRootPane().registerKeyboardAction(escListener,
                KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0),
                JComponent.WHEN_IN_FOCUSED_WINDOW);

    }
}

Related Tutorials