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

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

    Here's mine, I add CtrlW as closing shorcut aswell

        Action closeAction = new AbstractAction(){
            public void actionPerformed(ActionEvent e){
                dispose();
            }
        };
    
        KeyStroke esc = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE,0);
        getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(esc, "closex");
        getRootPane().getActionMap().put("closex", closeAction);
    
        KeyStroke ctrlW = KeyStroke.getKeyStroke("control W");
        getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(ctrlW, "close");
        getRootPane().getActionMap().put("close", closeAction); 
    

提交回复
热议问题