Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Close a dialog by pressing Enter

Tags:

java

dialog

swing

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?

like image 955
Jakub Zaverka Avatar asked Apr 25 '12 22:04

Jakub Zaverka


1 Answers

Two things:

  1. Have you tried using the setDefaultButton?: dialog.getRootPane().setDefaultButton(okButton)
  2. You could consider invoke your requestFocusInWindow() in an invokeLater.

Like this:

 SwingUtilities.invokeLater(new Runnable()
     @Override
     public void run() {
         okButton.requestFocusInWindow();
     }
 });
like image 95
Guillaume Polet Avatar answered Sep 27 '22 20:09

Guillaume Polet