Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 834
Prabhakaran Avatar asked Dec 05 '25 04:12

Prabhakaran


1 Answers

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); 
like image 187
Juh_ Avatar answered Dec 07 '25 18:12

Juh_