简体   繁体   English

按Enter键关闭对话框

[英]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. 我希望OK按钮具有焦点,因此用户只需调用对话框并按Enter即可创建具有默认值的新对象。 I tried calling requestFocusInWindow() , but that doesn't work until the window is actually shown. 我尝试调用requestFocusInWindow() ,但是在窗口实际显示之前不起作用。 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. 并且对话框类中没有像setInitialFocusedComponent()这样的方法。

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. 好的,那么我继续为对话框中的每个字段创建一个KeyListener (只有3个,没什么大不了的),如果用户按Enter键就会手动按OK按钮。 The problem now is that the first field (and therefore the focused one) is a JSpinner , which consumes its own KeyEvents . 现在的问题是第一个字段(因此是焦点字段)是一个JSpinner ,它使用自己的KeyEvents So pressing Enter does nothing. 所以按Enter键什么也没做。

How can I achieve this "Enter to OK" behaviour on my dialog without reorganizing the elements? 如何在不重新组织元素的情况下在对话框中实现“Enter to OK”行为?

Two things: 两件事情:

  1. Have you tried using the setDefaultButton?: dialog.getRootPane().setDefaultButton(okButton) 您是否尝试过使用setDefaultButton?: dialog.getRootPane().setDefaultButton(okButton)
  2. You could consider invoke your requestFocusInWindow() in an invokeLater. 您可以考虑在invokeLater中调用requestFocusInWindow()。

Like this: 像这样:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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