Retrofitting type ahead to Eclipse SWT combo

When you have a combo box with lots of items it is convenient for the end-user to be able to select an item by typing the first few characters of its name. Unfortunately the SWT combo box only searches for one character (at least in Windows XP) making combo boxes with lots of items cumbersome to use.

This shortcoming can be addressed by adding a key listener to the combo that keeps track of typed characters and performs the search and blocks the default behaviour. It seems like a very simple thing but it isn’t quite obvious how you want the combo to behave. In my use case I found that the following characteristics worked well:

  • Collect letters and digits as they are typed. For other input clear the search string.
  • Use the entered string for case-insensitive search
  • If the user stops typing (e.g. no input the last second) the search string is cleared.
  • If no item starts with the search string it is cleared (assuming that the user made a typo).
final String[] items = new String[] {"beige", "black", "BLUE", "brown"};

final Combo combo = new Combo(shell, SWT.READ_ONLY);
combo.addKeyListener(new KeyAdapter(){
   private long sequenceTimeOut = 0;
   private String keySequence;

   public void keyPressed(KeyEvent keyEvent){
      if (!Character.isLetterOrDigit(keyEvent.character)){
      long now = System.currentTimeMillis();
      if (now > sequenceTimeOut){
         keySequence = "";
      keySequence += Character.toLowerCase(keyEvent.character);
      sequenceTimeOut = now + 1000;
      int index = 0;
      for (String item : items){
         if (item.toLowerCase().startsWith(keySequence)){
            // Prevent the ordinary search
            keyEvent.doit = false;
      keySequence = "";

This Post Has One Comment

  1. JF

    Thanks for your solution. The default behaviour is really annoying.

Leave a Reply