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
*/

thisFrame=this;

// Call the method
createAndShowGUI();
}

private void createAndShowGUI()
{
// set frame properties
setTitle("Escape JDialog");
setSize(400,400);
setLayout(new FlowLayout());
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);

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());
jd.setVisible(true);

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

// pack it up
jd.pack();

// create ActionListener
ActionListener a=new ActionListener(){
public void actionPerformed(ActionEvent ae)
{
jd.dispose();
}
};

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

jd.getRootPane().registerKeyboardAction(a,KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE,0),JComponent.WHEN_IN_FOCUSED_WINDOW);
}
});

add(jb);
}

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.

No comments: