Java JTextField make ENTER key transfer focus

Description

Java JTextField make ENTER key transfer focus

import java.awt.BorderLayout;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

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

public class Main {
   public static void main(String[] argv) throws Exception {
      MyTextField component = new MyTextField(10);
      /*from   w w w  . j a  va 2  s . c om*/
      JFrame f = new JFrame();

      f.add(component, BorderLayout.NORTH);
     
      f.add(new JTextField(10), BorderLayout.SOUTH);
      f.setSize(300, 300);
      f.setVisible(true);
   }
}

class MyTextField extends JTextField {
  MyTextField(int len) {
    super(len);
    addKeyListener(new KeyAdapter() {
      public void keyPressed(KeyEvent evt) {
        int key = evt.getKeyCode();
        if (key == KeyEvent.VK_ENTER)
          transferFocus();
      }
    });
  }
}



PreviousNext

Related