2010-12-19 139 views
0

我想在基於for和if循環的ArrayList中設置JCombobox中的值。JComboBox沒有顯示結果

 //salesman=the name of the combobox 
    salesman = new javax.swing.JComboBox(); 

DefaultComboBoxModel model = new DefaultComboBoxModel(); 
salesman.setModel(model); 

/*company is an object of Company class, that gets set with a setter method to ensure 
that the gui will be pointing to the right object. and it does contains the data i want, so 
i am sure that company is not the problem */  
//loop tp set box list 
for (Employee current : company.getArray()){ 

if (current instanceof Salesman) { 
    salesman.addItem(current.getCode()); 
    } 

} 

但是組合框保持空白。這是爲什麼 ?

+0

實際上,它可能不是空的(但相當小,如果* Salesman.getCode()。toString()*返回空:)) – 2010-12-19 13:03:23

回答

0

您是否將組合框添加到其父容器?

只要有一些推銷員在場,上面的代碼應該可以正常工作。

你說你確定公司不是對象,但你有沒有檢查你實際添加到ComboBoxModel的內容?此外,您不需要實例化自己的DefaultComboBoxModel,因爲您可以通過JComboBox「免費」獲得一個DefaultcomboBoxModel

+0

我寫了一個測試方法,打印「當前」的值。 當我調用另一個JFrame調用這個方法(通過使用AddOrder.test();它打印我兩個代碼(45,46) – George 2010-12-19 13:03:08

0

如果您只是將一些測試字符串添加到JComboBox,它們是否顯示?

如果它們是.getCode()方法可能有問題。

此外,請嘗試刪除DefaultComboBoxModel,因爲這不是必需的。

+0

如果手動添加salesman.addItem(「blablabla」);,它getCode()除了返回推銷員密碼外什麼都沒做, – George 2010-12-19 14:17:57

2

無論如何,我建議你以下:

  1. 覆蓋的的toString()推銷員類的方法以具有期望的可視化表示(即代碼)。

  2. 添加推銷員,而不是代碼組合框模型

1

將項目添加到模型不直接到組合框。另外,請使用barti_ddu的建議。

0

好問題已解決!我只是向該類的構造函數添加了一個Company類對象,該對象使用setCompany進行設置。

+0

你設法解決你的問題很好,現在你需要將其中一個答案標記爲你接受的答案 - 或者標記你自己的答案,你發現最有用的。 – BoffinbraiN 2010-12-23 15:43:30