How to close JDialog on Escape

I am frustrated when i wanted to close JDialog on Escape method. Now finally i got it. I encountered a method which will do the thing. I think you might be enthusiastic to know that method. Let me show how to do this and how the method works.
Let me first explain the prototype of the method registerKeyboardAction()

registerKeyboardAction(ActionListener a, KeyStroke s, int aCondition) In this the ActionListener contains the method actionPerformed() which contains the code that escapes the dialog (here). The KeyStroke object which can be obtained by the getKeyStroke() static method in KeyStroke is used to specify the key along with the modifier if we wish to. The aCondition is the condition when to fire this event. In this example i'll be using the condition when the component is in a focused window.

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class EscapeJDialog extends JFrame
private JButton jb;
private JFrame thisFrame;
public EscapeJDialog()

/* this cannot be used directly to represent
* this object when in anonymous inner class


// Call the method

private void createAndShowGUI()
// set frame properties
setTitle("Escape JDialog");
setLayout(new FlowLayout());

jb=new JButton("Open JDialog");
jb.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae)
// Parent is this frame
final JDialog jd=new JDialog(thisFrame);
jd.setTitle("Escape JDialog");
jd.setLayout(new FlowLayout());

// add some sample components
jd.add(new JTextField(10));
jd.add(new JButton("Button!"));

// pack it up

// create ActionListener
ActionListener a=new ActionListener(){
public void actionPerformed(ActionEvent ae)

* Register the actionlistener which should
* be fired on ESCAPE when the rootpane is
* in focused window



public static void main(String args[])
new EscapeJDialog();

Output of the program

Closing JDialog on escape using ActionListener

In this way we can close JDialog on Escape. Simple is that.

Posted by at on

Tags: Swing Hacks,