Java Swing How to - Make Enter Key to behave as Tab on an Editable JComboBox








Question

We would like to know how to make Enter Key to behave as Tab on an Editable JComboBox.

Answer

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.FlowLayout;
//ww w. j a  v  a 2s.c o m
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class Main {
  public static void main(String[] args) {
    JComboBox<String> comboBox = new JComboBox<>(new String[] { "A", "B", "C" });
    comboBox.setEditable(true);

    JTextField editorComponent = (JTextField) comboBox.getEditor()
        .getEditorComponent();
    editorComponent.addActionListener(e -> {
      editorComponent.transferFocus();
    });

    JPanel panel = new JPanel(new FlowLayout());
    panel.add(new JLabel("Field 1"));
    panel.add(comboBox);
    panel.add(new JLabel("Field 2"));
    panel.add(new JTextField(10));
    panel.add(new JLabel("Field 3"));
    panel.add(new JTextField(10));

    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setLocationRelativeTo(null);

    Container c = frame.getContentPane();
    c.setLayout(new BorderLayout());
    c.add(panel, BorderLayout.CENTER);
    frame.pack();
    frame.setVisible(true);
  }
}