Friday 26 February 2016

Java Swing GUI's default and cancel buttons

None of these are mine. I just copied and re-factored them from here and here in stackoverflow.com.

The code comes from a login form that needs to have it's login button clicked when enter is pressed and to be closed when user hits escape.

Other frameworks like good old VCL and WindowsForms allow this to be done by visually managing properties, but with Java you have to type something like this :

        // set default botton on ENTER
        this.getRootPane().setDefaultButton(jButtonLogin);

        // set escape to close this dialog
        KeyStroke escapeKeyPressed = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0);        
        this.getRootPane().registerKeyboardAction( e -> this.dispose(), escapeKeyPressed, JComponent.WHEN_IN_FOCUSED_WINDOW);

Enjoy.