Here is what you need to do.
create an arrayList or List and add all your items there.
Create combobox and and loops all your items and add it to comboBox
Then create a filter method.
This is not a perfect answer but it will get you going.
public class FilterComboBoxText {
private JFrame frame;
private final JComboBox comboBox = new JComboBox();
private static List<String>listForComboBox= new ArrayList<String>();
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
FilterComboBoxText window = new FilterComboBoxText();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
listForComboBox.add("Lion");
listForComboBox.add("LionKing");
listForComboBox.add("Mufasa");
listForComboBox.add("Nala");
listForComboBox.add("KingNala");
listForComboBox.add("Animals");
listForComboBox.add("Anims");
listForComboBox.add("Fish");
listForComboBox.add("Jelly Fish");
listForComboBox.add("I am the boss");
}
public FilterComboBoxText() {
initialize();
}
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 412, 165);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
comboBox.setEditable(true);
comboBox.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent arg0) {
}
});
for(String detail : listForComboBox) {
comboBox.addItem(detail);
}
final JTextField textfield = (JTextField) comboBox.getEditor().getEditorComponent();
textfield.addKeyListener(new KeyAdapter() {
public void keyReleased(KeyEvent ke) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
if(!textfield.getText().isEmpty()){
comboBoxFilter(textfield.getText());
}
}
});
}
});
comboBox.setBounds(10, 39, 364, 29);
frame.getContentPane().add(comboBox);
}
public void comboBoxFilter(String enteredText) {
System.out.println(comboBox.getItemCount());
if (!comboBox.isPopupVisible()) {
comboBox.showPopup();
}
List<String> filterArray= new ArrayList<String>();
for (int i = 0; i < listForComboBox.size(); i++) {
if (listForComboBox.get(i).toLowerCase().contains(enteredText.toLowerCase())) {
filterArray.add(listForComboBox.get(i));
}
}
if (filterArray.size() > 0) {
DefaultComboBoxModel<String> model = (DefaultComboBoxModel<String>) comboBox.getModel();
model.removeAllElements();
model.addElement("");
for (String s: filterArray)
model.addElement(s);
JTextField textfield = (JTextField) comboBox.getEditor().getEditorComponent();
textfield.setText(enteredText);
}
}
}