Close a dialog by pressing Enter

dialog, java, swing

Solution

Two things:

- Have you tried using the setDefaultButton?: `dialog.getRootPane().setDefaultButton(okButton)`

- You could consider invoke your requestFocusInWindow() in an invokeLater.

Like this:

 SwingUtilities.invokeLater(new Runnable()
     @Override
     public void run() {
         okButton.requestFocusInWindow();
     }
 });

Problem

I have a peculiar requirement: I have a Create new object modal dialog with a number of fields and buttons OK and Cancel. I want the OK button to have focus, so the user can simply invoke the dialog and press Enter to create a new object with default values. I tried calling `requestFocusInWindow()`, but that doesn't work until the window is actually shown. I cannot call it after the window is shown, because the dialog is modal. And there is no method like `setInitialFocusedComponent()` on the dialog class. OK, so then I proceeded to create a `KeyListener` for every field in the dialog (only 3 of them, no big deal), that would manually press the OK button if user hit Enter on them. The problem now is that the first field (and therefore the focused one) is a `JSpinner`, which consumes its own `KeyEvents`. So pressing Enter does nothing. How can I achieve this "Enter to OK" behaviour on my dialog without reorganizing the elements?

Original source