Java ActionListener handle enter key pressed event for JTextField

Description

Java ActionListener handle enter key pressed event for JTextField

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JFrame;
import javax.swing.JTextField;

public class Main extends JFrame {
  JTextField text = new JTextField("Press Return", 40);

  public Main() {
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    text.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        System.out.println("Text=" + text.getText());
      }/*from   w  w w  .ja  va 2  s  .  c  om*/
    });

    getContentPane().add(text, "North");
    pack();
  }

  public static void main(String[] args) {
    new Main().setVisible(true);
  }
}



PreviousNext

Related