javaswingdefaultbutton

Fire Default Button on jTextField Action Performed


In my program have a JButton and JTextField.
I want jButton fire while press Enter key in JTextField
I'm not talking about KeyEvent.

private void jTextFieldActionPerformed(java.awt.event.ActionEvent evt) {                                            
    this.getRootPane().setDefaultButton(jButton1);
}

This just make JButton focus enabled after enter in JTextField
So when I will enter in JTextField it must fire JButton ActionEvent.

And have this code on jButton1 ActionPerformed method.

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        JOptionPane.showMessageDialog(rootPane, "Hi!");
    } 

So how can I make JButton fired on JTextField ActionEvent?
I tried following answer but in IDE it throwing exception.

Exception in thread "AWT-EventQueue-0" java.lang.RuntimeException: Uncompilable source code - Erroneous sym type: javax.swing.JButton.addActionListener 

Solution

  • One way to achieve that (if i got this straight), is to add an ActionListener to the JTextField which will call JButton#doClick() method. (I think it is pretty clear what the doClick() method does).

    An example:

    import java.awt.FlowLayout;
    
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JTextField;
    import javax.swing.SwingUtilities;
    
    public class FireButtonOnEnter extends JFrame {
        private static final long serialVersionUID = -7346953935931623335L;
    
        public FireButtonOnEnter() {
            setDefaultCloseOperation(EXIT_ON_CLOSE);
            setSize(400, 400);
            setLocationRelativeTo(null);
            getContentPane().setLayout(new FlowLayout());
            JTextField textField = new JTextField(15);
            JButton button = new JButton("Print Hello");
            button.addActionListener(e -> System.out.println("Hello world."));
            textField.addActionListener(e -> button.doClick());
            getContentPane().add(textField);
            getContentPane().add(button);
        }
    
        public static void main(String[] args) {
            SwingUtilities.invokeLater(() -> new FireButtonOnEnter().setVisible(true));
        }
    }