Java Swing How to - Disable the first item on a JComboBox








Question

We would like to know how to disable the first item on a JComboBox.

Answer

import java.awt.BorderLayout;
import java.awt.FlowLayout;
//  w  ww.  j  av a  2 s  .co m
import javax.swing.JComboBox;
import javax.swing.JFrame;

public class Main extends JFrame {
  JComboBox<String> states;

  public Main() {
    super();
    states = new JComboBox<String>(
        new String[] { "Select a State", "AL", "AK", "AZ", "AR", "CA", "CO",
            "CT", "DE", "FL", "GA", "HI", "ID", "IL", "IN", "IA", "KS", "KY",
            "LA", "ME", "MD", "MA", "MI", "MN", "MS", "MO", "MT", "NE", "NV",
            "NH", "NJ", "NM", "NY", "NC", "ND", "OH", "OK", "OR", "PA", "RI",
            "SC", "SD", "TN", "TX", "UT", "VT", "VA", "WA", "WV", "WI", "WY" });

    setLayout(new FlowLayout(FlowLayout.CENTER));
    add(states, BorderLayout.CENTER);

    states.addItemListener(e -> {
      if (states.getSelectedIndex() > 0) {
        System.out.println("YOU CLICK INDEX- " + states.getSelectedIndex());
      }
    });
  }

  public static void main(String[] args) {
    Main g = new Main();
    g.setVisible(true);
    g.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    g.setBounds(100, 100, 300, 300);
  }
}