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

前端 未结 5 1275
春和景丽
春和景丽 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:07

    I had problems implementing both of the top answers. Here's a rather compact version using AbstractAction to auto-implement most of Action's methods, which works within text-based fields (per @pratikabu's request):

    final AbstractAction escapeAction = new AbstractAction() {
        private static final long serialVersionUID = 1L;
    
        @Override
        public void actionPerformed(ActionEvent ae) {
            dispose();
        }
    };
    
    getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW)
            .put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), "ESCAPE_KEY");
    getRootPane().getActionMap().put("ESCAPE_KEY", escapeAction);
    

    References

    • the above answers
    • http://www.coderanch.com/t/335357/GUI/java/KeyPressed-JDialog

提交回复
热议问题