Make the ENTER key act like the TAB key in Java

Description

The following code shows how to make the ENTER key act like the TAB key.

Example


/*from w  w w.  ja v a2  s .c o  m*/
import java.awt.FlowLayout;
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[] args) {
    JFrame f = new JFrame("Text Field Elements");
    
    f.setLayout(new FlowLayout());
    f.add(new MyTextField(3));
    f.add(new MyTextField(3));
    f.add(new MyTextField(3));
    f.add(new MyTextField(3));
    f.pack();
    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();
      }
    });
  }
}

The code above generates the following result.

Make the ENTER key act like the TAB key in Java




















Home »
  Java Tutorial »
    Swing »




Action
Border
Color Chooser
Drag and Drop
Event
Font Chooser
JButton
JCheckBox
JComboBox
JDialog
JEditorPane
JFileChooser
JFormattedText
JFrame
JLabel
JList
JOptionPane
JPasswordField
JProgressBar
JRadioButton
JScrollBar
JScrollPane
JSeparator
JSlider
JSpinner
JSplitPane
JTabbedPane
JTable
JTextArea
JTextField
JTextPane
JToggleButton
JToolTip
JTree
Layout
Menu
Timer