tags:

views:

21

answers:

2

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);
  }
}
+1  A: 

OK, I'm stupid... Just subclass JComboBox and add:

@Override
protected void selectedItemChanged() {
    fireItemStateChanged(new ItemEvent(this, ItemEvent.ITEM_STATE_CHANGED,
            selectedItemReminder,
            ItemEvent.DESELECTED));
    selectedItemReminder = dataModel.getSelectedItem();

    fireItemStateChanged(new ItemEvent(this, ItemEvent.ITEM_STATE_CHANGED,
            selectedItemReminder,
            ItemEvent.SELECTED));
}

I still think the described behavior of JComboBox is inconsistent and confusing...

Landei
+1  A: 

Null objects will not play nicely in a JComboBox. For example, the combo box's getSelectedIndex method, which is fired when you select an item, will return -1 if the object is null. 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:

class StringWrapper{
    final String s;
    public StringWrapper(String s){
        this.s=s;
    }
    @Override
    public String toString() {
        return s;
    }
}

final JComboBox cb = new JComboBox(new StringWrapper[]{ 
            new StringWrapper(null), 
            new StringWrapper("one"),
            new StringWrapper("two"),
            new StringWrapper("three")});
dogbane
I didn't implemented it that way, but the hint regarding which methods misbehave was very useful...
Landei