To disable the first index, on the click of a button, let us implement for index > 0 i.e. item 2:
System.out.println("Index 0 (First Item) is disabled... ");
comboBox.addItemListener(e -> {
if (comboBox.getSelectedIndex() > 0) {
System.out.println("Index = " + comboBox.getSelectedIndex());
}
});
By implementing above, we have disabled the first item.
The following is an example to disable the first item on a JComboBox:
Example
import javax.swing.*;
public class SwingDemo {
JFrame frame;
SwingDemo(){
frame = new JFrame("ComboBox");
String Sports[]={"Select","Tennis","Cricket","Football"};
JComboBox comboBox = new JComboBox(Sports);
comboBox.setBounds(50, 50,90,20);
frame.add(comboBox);
frame.setLayout(null);
frame.setSize(400,500);
frame.setVisible(true);
System.out.println("Index 0 (First Item) is disabled... ");
comboBox.addItemListener(e -> {
if (comboBox.getSelectedIndex() > 0) {
System.out.println("Index = " + comboBox.getSelectedIndex());
}
});
}
public static void main(String[] args) {
new SwingDemo();
}
}
The output is as follows. You can now select all the indexes except index 0 (first item). Let us select the first index i.e. the second item:
Output
Meanwhile, while selecting Tennis above, the following is displayed on Console: