cmbMake = new JComboBox();
cmbMake.addItem("**Please Select**");
Iterator i = products.entrySet().iterator();
while (i.hasNext())
{
Map.Entry me = (Map.Entry) i.next();
Product p = (Product) me.getValue();
if(!p.getMake().equals(cmbMake.getSelectedItem()))
{
cmbMake.addItem("" + p.getMake());
}
}
我有一个保存产品详细信息的类,是否有同样的方法来阻止将同一品牌添加到组合框中?
答案 0 :(得分:1)
假设make是String,只需创建一个包含所有不同值的集合,然后将它们添加到ComboBox:
Set<String> productMakes = new HashSet<String>();
for (Map.Entry<KeyClass, Product> productEntry: products.entrySet()) {
productMakes.add(productEntry.getValue().getMake());
}
// How about sorting the items before adding them to the ComboBox?
List<String> sortedProductMakes = new ArrayList<String>(productMakes);
java.util.Collections.sort(sortedProductMakes);
for (String productMake : sortedProductMakes ) {
cmbMake.addItem(productMake);
}
答案 1 :(得分:1)
您可以尝试使用此代码(我在您的代码中添加了一些代码)。该代码获取 makes 的值并将其存储在Set集合中,然后填充组合框。
cmbMake = new JComboBox();
cmbMake.addItem("**Please Select**");
Iterator i = products.entrySet().iterator();
Set<String> uniqueMakes = new HashSet<>(); // this stores unique makes
while (i.hasNext())
{
Map.Entry me = (Map.Entry) i.next();
Product p = (Product) me.getValue();
//if(! p.getMake().equals(cmbMake.getSelectedItem()))
//{
// cmbMake.addItem("" + p.getMake());
//}
uniqueMakes.add(p.getMake());
}
System.out.println(uniqueMakes); // this prints the makes
// Add makes to the combo box
for (String make : uniqueMakes) {
cmbMake.addItem(make);
}
建议:您可以在使用其中一些参数时使用类型参数,例如:
JComboBox<String> cmbMake = new JComboBox<>();
Iterator<Product> i = products.entrySet().iterator();
编辑:这是有关using Set collection和using Generics的教程。
EDIT(使用函数式编程对相同功能进行编码的另一种方式):
cmbMake = new JComboBox<String>();
cmbMake.addItem("**Please Select**");
products.values()
.map(product -> product.getMake())
.collect(Collectors.toCollection(HashSet::new))
.forEach(make -> cmbMake.addItem(make));
答案 2 :(得分:1)
将所有值添加到Set
并对其进行迭代:
for(Object o : new HashSet<>(products.values())){
Product p = (Product) o.getValue();
if(!p.getMake().equals(cmbMake.getSelectedItem())) {
cmbMake.addItem("" + p.getMake());
}
}
答案 3 :(得分:-1)
尝试此代码,
cmbMake = new JComboBox();
cmbMake.addItem("**Please Select**");
Map products = null;
Iterator i = products.entrySet().iterator();
while (i.hasNext()) {
Map.Entry me = (Map.Entry) i.next();
Product p = (Product) me.getValue();
Set<String> productSet = new HashSet<String>();
productSet.add(p.getMake());
if (!p.getMake().equals(cmbMake.getSelectedItem())) {
if (productSet.size() > 0) {
productSet.forEach(action -> {
cmbMake.addItem("" + action);
});
}
}
}