2010-10-22 66 views
2

看起來沒有選擇或取消選擇ItemEvent s是爲JComboBox中的空項目生成的。我該如何改變這一點?製作項目""不是一個選項。JComboBox - no ItemEvents for null-items

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

回答

2

空對象在JComboBox中不會很好地發揮。例如,如果對象是null,則在選擇某個項目時激發的組合框的getSelectedIndex方法將返回-1。也可能有其他方法執行空檢查並可能返回不正確的結果。

如果您確實需要此功能,最好使用包裝對象。例如:

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

我沒有這樣實施,但關於哪些方法行爲不當的提示非常有用...... – Landei 2010-10-26 11:39:17

2

OK,我傻......只要繼承的JComboBox並添加:

@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)); 
} 

我仍然認爲JComboBox中所描述的行爲是不一致的混亂...

+0

這幫助我。我也重寫了getSelectedIndex()來刪除它的檢查null。箭頭到列表中的項目時,行爲仍然有點奇怪,但除此之外沒有問題。下面是getSelectedIndex()中被更改的行: if(obj == sObject ||(obj!= null && obj.equals(sObject))) \t return i; – Pixel 2012-06-11 17:23:49

0

如果您希望觸發一次當條目經選擇,包括空動作......

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