title: Escape button with Jpanel or JFrame or Dialog
body: <p>I am creating an application in which any opened <strong>Jpanel</strong> or <strong>JFrame</strong> or <strong>Dialog</strong> should be closed on striking <strong>Escape</strong> button of the keyboard.</p>
  
  <p>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.</p>
  
  <p>Please assist me if I am doing any thing wrong</p>
  
  <p>Thanks in advance...</p>
  
  <p>My method is</p>
  
  <pre><code>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 ");
       }
  </code></pre>