当按下回车键时,JFrame 中的默认按钮不触发

2022-09-03 02:45:37

我有一个带有三个JButtons的东西。我已经设置(一个组件)在加载时具有焦点。其中一个按钮设置为默认按钮。这是我的代码:JFrametxtSearchJTextFieldJFrame

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

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

答案 1

当出现时,哪个组件具有焦点?我问,因为有些组件“吃”了Enter键事件。例如,a 会这样做。JFrameJEditorPane

此外,当您将 分配给 时,将调用 ,而不是根窗格的 。您必须选择具有 或 ,但不能同时具有 两个火。我相信这也适用于其他组件。ActionListenerJTextFieldActionListenerDefaultButtonActionListenerDefaultButtonJTextField


答案 2

我从发布的内容中看不到您做错了什么。下面是一个有效的简短示例。也许它会揭示一些对你有用的东西。

import java.awt.BorderLayout; 
public class ExampleFrame extends JFrame 
{
  private JPanel    m_contentPane;
  private JTextField m_textField;

  /**
   * Launch the application.
   */
  public static void main(String[] args)
  {
    EventQueue.invokeLater(new Runnable()
    {
        public void run()
        {
            try
            {
                ExampleFrame frame = new ExampleFrame();
                frame.setVisible(true);
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
        }
    });
  }

  /**
  * Create the frame.
   */
  public ExampleFrame()
  {
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setBounds(100, 100, 450, 300);
    m_contentPane = new JPanel();
    m_contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
    m_contentPane.setLayout(new BorderLayout(0, 0));
    setContentPane(m_contentPane);

    m_textField = new JTextField();
    m_contentPane.add(m_textField, BorderLayout.NORTH);
    m_textField.setColumns(10);

    JButton btnNewButton = new JButton("Default");
    btnNewButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            JOptionPane.showMessageDialog(ExampleFrame.this, "Default.");
        }
    });
    m_contentPane.add(btnNewButton, BorderLayout.CENTER);

    JButton btnNewButton_1 = new JButton("Not default");
    btnNewButton_1.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            JOptionPane.showMessageDialog(ExampleFrame.this, "Not default.");
        }
    });
    m_contentPane.add(btnNewButton_1, BorderLayout.WEST);
    m_textField.requestFocus();
    getRootPane().setDefaultButton(btnNewButton);
  }
}