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

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

    If your looking for a technique using new features of Java 8 , try a lambda expression:

    dialog.getRootPane().registerKeyboardAction(e -> {
        window.dispose();
    }, KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), JComponent.WHEN_IN_FOCUSED_WINDOW);
    

    or

    KeyStroke k = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0);
    int w = JComponent.WHEN_IN_FOCUSED_WINDOW;
    dialog.getRootPane().registerKeyboardAction(e -> window.dispose(), k, w);
    

提交回复
热议问题