我正在尝试在arraylist上基于for和if循环在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 :(得分:2)
无论如何,我建议您使用以下内容:
覆盖 Salesman 类的 toString() 方法,以获得理想的视觉效果(即码)。
添加销售人员,而非代码 模型 。
答案 1 :(得分:1)
将项目添加到模型中而不是直接添加到ComboBox。另外,也可以使用barti_ddu的建议。
答案 2 :(得分:0)
您是否将组合框添加到其父容器中?
只要Salesman存在一些实例,上述代码就可以正常工作。
你说你确定公司不是对象,但是你检查了你实际添加到ComboBoxModel的内容了吗?此外,您不需要实例化您自己的DefaultcomboBoxModel,因为您使用JComboBox“免费”获得一个
答案 3 :(得分:0)
如果您只是将一些测试字符串添加到JComboBox,它们会显示吗?
如果它们可能是.getCode()方法可能有问题。
另外,请尝试删除DefaultComboBoxModel,因为这不是必需的。
答案 4 :(得分:0)
确定问题解决了!我刚刚在类的构造函数中添加了一个使用setCompany设置的Company类对象。