Share this page 

React to the ENTER key in a TextfieldTag(s): AWT


import java.applet.*;
import java.awt.*;
import java.awt.event.*;

public class testENTER extends Applet
    implements KeyListener {
  TextField t;
  public void init(){
    TextField t = new TextField("press ENTER");
    add(t);
    t.addKeyListener(this);
    }
   public void keyTyped(KeyEvent e) {}
   public void keyReleased(KeyEvent e) {}
   public void keyPressed(KeyEvent e) {
     int key = e.getKeyCode();
     if (key == KeyEvent.VK_ENTER) {
        Toolkit.getDefaultToolkit().beep(); 
        System.out.println("ENTER pressed");
        }
     }
}
Or the short version using the KeyAdapter class.
import java.applet.*;
import java.awt.*;
import java.awt.event.*;

public class testENTER extends Applet{
  TextField t;
  public void init(){
    TextField t = new TextField("press ENTER");
    add(t);
    t.addKeyListener
      (new KeyAdapter() {
         public void keyPressed(KeyEvent e) {
           int key = e.getKeyCode();
           if (key == KeyEvent.VK_ENTER) {
              Toolkit.getDefaultToolkit().beep();   
              System.out.println("ENTER pressed");
              }
           }
         }
      );
    }
}