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

前端 未结 5 1294
春和景丽
春和景丽 2020-12-24 00:52

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 contain

5条回答
  •  春和景丽
    2020-12-24 01:04

    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);
    
    }
    

提交回复
热议问题