Java Swing How to - Create Auto suggested JComboBox








Question

We would like to know how to create Auto suggested JComboBox.

Answer

import java.awt.BorderLayout;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
//from  w  w  w .  j  av a  2 s . c o m
import javax.swing.ComboBoxEditor;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.plaf.basic.BasicComboBoxEditor;

public class Main {
  public static void main(String[] args) {
    JFrame fr = new JFrame();
    JPanel p = new JPanel();
    p.setLayout(new BorderLayout());
    String[] ss = new String[] { "112", "1223", "1124", "1134" };
    fr.getContentPane().add(p);
    AutoCompleteComboBox cb = new AutoCompleteComboBox(ss);

    p.add("South", cb);
    p.add("Center", new JButton("test combo box"));
    fr.pack();
    fr.setVisible(true);
  }
}

class AutoCompleteComboBox extends JComboBox {
  public int caretPos = 0;
  public JTextField tf = null;

  public AutoCompleteComboBox(final Object items[]) {
    super(items);
    this.setEditor(new BasicComboBoxEditor());
    this.setEditable(true);
  }

  public void setSelectedIndex(int ind) {
    super.setSelectedIndex(ind);
    tf.setText(getItemAt(ind).toString());
    tf.setSelectionEnd(caretPos + tf.getText().length());
    tf.moveCaretPosition(caretPos);
  }

  public void setEditor(ComboBoxEditor anEditor) {
    super.setEditor(anEditor);
    if (anEditor.getEditorComponent() instanceof JTextField) {
      tf = (JTextField) anEditor.getEditorComponent();
      tf.addKeyListener(new KeyAdapter() {
        public void keyReleased(KeyEvent ev) {
          char key = ev.getKeyChar();
          if (!(Character.isLetterOrDigit(key) || Character.isSpaceChar(key))){
            return;
          }
          String s = tf.getText();
          caretPos = tf.getCaretPosition();
          try {
            String text = tf.getText(0, caretPos);
            int n = getItemCount();
            for (int i = 0; i < n; i++) {
              int ind = ((String) getItemAt(i)).indexOf(text);
              if (ind == 0) {
                setSelectedIndex(i);
                return;
              }
            }
          } catch (Exception ex) {
            ex.printStackTrace();
          }
        }
      });
    }
  }
}