Java Swing How to - Handle keypress event for JComboBox








Question

We would like to know how to handle keypress event for JComboBox.

Answer

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
/*from w  w w  . ja v a  2  s.  c  o  m*/
import javax.swing.JComboBox;
import javax.swing.JFrame;

public class Main {
  public static void main(String args[]) {
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    String labels[] = { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J" };
    JComboBox<String> comboBox = new JComboBox<>(labels);
    comboBox.setEditable(true);

    comboBox.addActionListener(new ActionListener() {
      boolean found = false;

      @Override
      public void actionPerformed(ActionEvent actionEvent) {
        String s = (String) comboBox.getSelectedItem();
        for (int i = 0; i < comboBox.getItemCount(); i++) {
          if (comboBox.getItemAt(i).toString().equals(s)) {
            found = true;
            break;
          }
        }
        if (!found) {
          System.out.println("Added: " + s);
          comboBox.addItem(s);
        }
        found = false;
      }
    });

    frame.add(comboBox);

    frame.pack();
    frame.setVisible(true);
  }
}