开发者

JComboBox - no ItemEvents for null-items

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'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")});


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...


If you want an action that fires once when an entry is selected, including null...

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) {
       final JComboBox cb = new JComboBox(new String[]{null, "one","two","three"});
       cb.addItemListener(new ItemListener(){
            public void itemStateChanged(ItemEvent e) {
                if (e.getStateChange() == ItemEvent.SELECTED || cb.getSelectedItem() == null)
                System.out.println(e);
            }
       });
       JOptionPane.showMessageDialog(null, cb);
  }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜