It seems no selected or deselected ItemEvents are generated for the null-item in the JComboBox. How can I change this? Making the item "" is not an option.
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.JComboBox;
import javax.swing.JOptionPane;
public class ComboBoxTest {
public static void main(String... args) {
JComboBox cb = new JComboBox(new String[]{null, "one","two","three"});
cb.addItemListener(new ItemListener(){
public void itemStateChanged(ItemEvent e) {
System.out.println(e);
}
});
JOptionPane.showMessageDialog(null, cb);
}
}
Null objects will not play nicely in a
JComboBox. For example, the combo box’sgetSelectedIndexmethod, which is fired when you select an item, will return -1 if the object isnull. There may also be other methods which perform null checks and may return incorrect results.If you really need this functionality, it would be better to use wrapper objects. For example: