Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swing: how do I close a dialog when the ESC key is pressed?

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 ?

like image 642
Leonel Avatar asked Mar 13 '09 14:03

Leonel


People also ask

How do I close dialog with ESC?

By default, dialog can be closed by pressing Esc key and clicking the close icon on the right of dialog header.

How to exit a JDialog?

In Microsoft Windows environments (95, 98, NT), users can press the Escape key to close dialog windows.


1 Answers

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);  } 
like image 50
Ayman Avatar answered Sep 22 '22 06:09

Ayman