GUI development with Swing.
I have a custom dialog for choosing a file to be opened in my application; its class extends javax.swing.JDialog
and contains, among other components, a JFileChooser
, which can be toggled to be shown or hidden.
The JFileChooser
component already handles the ESC key by itself: when the file chooser is shown (embedded in my dialog) and I press ESC, the file chooser hides itself.
Now I would like my dialog to do the same: when I press ESC, I want the dialog to close. Mind you, when the embedded file chooser is shown, the ESC key should only hide it.
Any ideas ?
By default, dialog can be closed by pressing Esc key and clicking the close icon on the right of dialog header.
In Microsoft Windows environments (95, 98, NT), users can press the Escape key to close dialog windows.
You can use the following snippet. This is better because the rootPane will get events from any component in the dialog. You can replace setVisible(false) with dispose() if you want.
public static void addEscapeListener(final JDialog dialog) { ActionListener escListener = new ActionListener() { @Override public void actionPerformed(ActionEvent e) { dialog.setVisible(false); } }; dialog.getRootPane().registerKeyboardAction(escListener, KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), JComponent.WHEN_IN_FOCUSED_WINDOW); }
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