Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

import javax.swing.JComboBox;

public class Main {
    public static void main(String[] argv) throws Exception {
        String[] items = { "A", "A", "B", "B", "C" };
        JComboBox cb = new JComboBox(items);

        cb.addKeyListener(new MyKeyListener());
    }
}

class MyKeyListener extends KeyAdapter {
    public void keyPressed(KeyEvent evt) {
        JComboBox cb = (JComboBox) evt.getSource();

        int curIx = cb.getSelectedIndex();

        char ch = evt.getKeyChar();

        JComboBox.KeySelectionManager ksm = cb.getKeySelectionManager();
        if (ksm != null) {
            int ix = ksm.selectionForKey(ch, cb.getModel());
            boolean noMatch = ix < 0;
            boolean uniqueItem = ix == curIx;

            if (noMatch || !uniqueItem) {
                cb.showPopup();
            }
        }
    }
}