按下回车键时,JFrame中的默认按钮不会触发 [英] Default button in JFrame is not firing when the enter key is being pressed
问题描述
我有一个 JFrame
,上面有三个JButton。我已设置 txtSearch
(一个 JTextField
组件)以便在 JFrame $时获得焦点c $ c>加载。其中一个按钮被设置为默认按钮。这是我的代码:
I have a JFrame
with three JButtons on it. I have set txtSearch
(a JTextField
component) to have the focus when JFrame
loads. One of the buttons is set as the default button. This is my code:
private void formWindowOpened(java.awt.event.WindowEvent evt)
{
// btnRefresh.setMnemonic(KeyEvent.VK_R); // Even if this line
// is not commented, but
// still the event wouldn't fire.
this.getRootPane().setDefaultButton(btnRefresh);
}
加载时,按钮刚刚被选中,但是当它按下时什么也没做正在按 Enter 键。我如何正确实现它?
When it loads, the button is just selected, but it did nothing when the Enter key was being pressed. How do I correctly implement it?
btnRefresh.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnRefreshActionPerformed(evt);
}
});
private void btnRefreshActionPerformed(java.awt.event.ActionEvent evt) {
JOptionPane.showMessageDialog(this, "Pressed!");
// Other codes here (Replace by JOptionPane)
}
推荐答案
当 JFrame
出现时,哪个组件有焦点?我问,因为一些组件吃掉Enter键事件。例如, JEditorPane
会这样做。
What component has focus when the JFrame
comes up? I ask because some components "eat" the Enter key event. For example, a JEditorPane
will do that.
此外,当您指定 ActionListener时
到 JTextField
,将调用 ActionListener
而不是根窗格的DefaultButton
。您必须选择具有 ActionListener
或 DefaultButton
,但是您不能同时使用的JTextField
。我确信这也适用于其他组件。
Also, when you assign an ActionListener
to JTextField
, the ActionListener
will be called instead of the DefaultButton
for the root pane. You must choose either to have an ActionListener
or a DefaultButton
, but you can't have both fire for the same JTextField
. I'm sure this applies to other components as well.
这篇关于按下回车键时,JFrame中的默认按钮不会触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!