I am creating an application in which any opened Jpanel or JFrame or Dialog should be closed on striking Escape button of the keyboard.
If I open any panel and direct hit Escape button that it is closed successfully without any problem.. but when I am trying to close it using Escape key after doing something in that JPanel or JFrame or Dialog, It is unable to close.
Please assist me if I am doing any thing wrong
Thanks in advance…
My method is
public static void addKeyBinding(JComponent c, final Object promptControl) {
debugLogger.debug("Start Escape Key Binding ");
Action escape = new AbstractAction() {
{
putValue(NAME, "escape");
}
public void actionPerformed(ActionEvent e) {
try {
JComponent source = (JComponent) e.getSource();
Window window = SwingUtilities.getWindowAncestor(source);
window.dispose();
Dialog dialog = (Dialog) source.getFocusCycleRootAncestor();
dialog.dispose();
debugLogger.debug("source = " + source.getClass().getName()
+ "\n"
+ "source.focusCycleRootAncestor = "
+ source.getFocusCycleRootAncestor().getClass().getName());
} catch (Exception ex) {
errorLogger.error("Exception caught while closing the window." + x.toString());
}
}
};
Object name = escape.getValue(Action.NAME);
c.getInputMap().put(KeyStroke.getKeyStroke("ESCAPE"), name);
c.getActionMap().put(name, escape);
debugLogger.debug("End Escape Key Binding ");
}
1) Use CardLayout instead of to create bunch of Top-Level Containers on Runtime
2) Re_use
Top-Level Containersby removing its content, because these containers are presents in the memory3) if you’ll re_use JDialogs then you have to call only
setVisible(true/fasle), better would be wrap visibilities to theinvokeLater()to add this event to EDTEDIT