Catching the Enter key event on a JTextField

The following example shows a JDialog with one JTextField. When the Enter key is detected, it will perform a doClick on the OK button.

Main.java:

import javax.swing.event.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
 
public class Main extends JDialog
{
   public Main() {
      getContentPane().setLayout(new GridLayout(2, 1, 20, 20)); 
      final JTextField inputField = new JTextField();
      getContentPane().add(inputField);
 
      final JButton okButton = new JButton("Ok");
      JButton cancelButton = new JButton("Cancel");
      JPanel panel = new JPanel(new GridLayout(1, 2));
      panel.add(okButton);
      panel.add(cancelButton);
 
      getContentPane().add(panel);     
        
      okButton.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent ae) {
            System.out.println("Ok pressed, textfield = " + inputField.getText());
            System.exit(0);
         }
      });
      cancelButton.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent ae) {
            System.out.println("Cancel pressed, textfield = " + inputField.getText());
            System.exit(0);
         }
      });
 
 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(0);
         }
      });
 
      // catch the enter key in the JTextField and perform an OK click on the JButton
      inputField.addKeyListener(new KeyAdapter() {
         public void keyPressed(KeyEvent e) {
            if (e.getKeyCode()==KeyEvent.VK_ENTER) {
               okButton.doClick();
            }
         }
      });
 
      pack();
      centerDialog();
   }
 
   public void centerDialog() {
      Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
      int x = (int) ((d.getWidth() - getWidth()) / 2);
      int y = (int) ((d.getHeight() - getHeight()) / 2);
      setLocation(x, y);
   }
 
   public static void main(String []args) {
      Main main = new Main();
      main.setVisible(true);
   }
}