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?
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With