简体   繁体   中英

Close a dialog by pressing Enter

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?

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();
     }
 });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM