'How to close the JFrame , if i pressing escape anywhere inside JFrame(not just in particular text box or etc.;)?

I know how to close jframe, if I'm in some text box or button,etc. By using keyPressed() method, I handle key events for text boxes,buttons. But, I want the jframe to be closed, when I press escape anywhere (not just in particular text fields,etc) inside jframe. Is it possible?



Solution 1:[1]

If the escape key stroke is not bound on the focussed sub-component, then the following should work:

// mainFrame is the JFrame

Action dispatchClosing = new AbstractAction() {
    public void actionPerformed(ActionEvent event) {
        mainFrame.dispatchEvent(
            new WindowEvent(mainFrame, WindowEvent.WINDOW_CLOSING));
        }
    };

KeyStroke escape = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE,0);

JRootPane rootPane = mainFrame.getRootPane();
rootPane.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(escape, "closeWindow");
rootPane.getActionMap().put("closeWindow", dispatchClosing); 

Solution 2:[2]

This should do it

public class ESC_Frame  implements KeyListener{
//Declaring few global variables
static JFrame frame = new JFrame("Press ESC to close");
static JLabel label;    

public static void main(String[] args) {    
    close();
}
public static void close(){
    ESC_Frame E = new ESC_Frame();
    
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(420,420);
    frame.setTitle("ESC to close"); 
    
    label = new JLabel("Press ESC to close");   
    
    frame.addKeyListener(E);
    frame.add(label);
    frame.setVisible(true);
}

@Override
public void keyPressed(KeyEvent e) {
    if (e.getKeyCode()==27)/*27 is int value returned when u press esc*/
    {
       frame.dispose();
    }       
}
//these next 2 methods have nothing to do with any of this, but u need to implement these methods 
@Override
public void keyReleased(KeyEvent e) {   
}
@Override
public void keyTyped(KeyEvent e) {      
}   

}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Juh_
Solution 2