Java Swing How to - Create case sensitive JComboBox








Question

We would like to know how to create case sensitive JComboBox.

Answer

//  ww w .  j a v  a 2s  . co  m
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;

import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class Main {

  public static void main(String[] args) {
    String items[] = { "Item1", "item1" };
    JFrame f = new JFrame();
    JPanel panel = new JPanel();
    JComboBox<String> combo = new JComboBox<>(items);
    combo.setEditable(true);

    JTextField txt = new JTextField(10);
    panel.add(combo);
    panel.add(txt);
    f.add(panel);
    combo.addItemListener(new ItemListener() {
      @Override
      public void itemStateChanged(ItemEvent ie) {
        String str = (String) combo.getSelectedItem();
        txt.setText(str);
      }
    });
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.setSize(400, 100);
    f.setVisible(true);
  }
}