2013-07-04 77 views
0

如何從HashMap填充JList,但只有列表中顯示值?從哈希映射填充JList並重試鍵

我正在用下面的代碼填充列表。當我啓動應用程序時,我得到像{1 = Value1},{2 = Value2}等列表項。我只想顯示值。

我使用的是HashMap,因爲我以後需要提交表單時,JList將使用從我的Insert方法中選擇的值的鍵,而我從其他例子中瞭解到這是使用hashsmap完成的。

public void populateListwithCategories(final JList list) { 
    try { 
     DefaultListModel listModel = new DefaultListModel(); 
     List<AdvertisementCategory> advertisementCategories = advertisementCategoryProvider.getAdvertisementCategories(); 
     for (AdvertisementCategory advertisementCategory : advertisementCategories) {    
      int id = advertisementCategory.getId(); 
      String name = advertisementCategory.getName(); 
      advertisementCategory.advertisementMap.put(id, name); 
      listModel.addElement(advertisementCategory.advertisementMap); 
     } 
     list.setModel(listModel); 
    } catch (MalformedURLException ex) { 
     Logger.getLogger(AdvertisementCategoryController.class.getName()).log(Level.SEVERE, null, ex); 
    } catch (IOException ex) { 
     Logger.getLogger(AdvertisementCategoryController.class.getName()).log(Level.SEVERE, null, ex); 
    } 
} 

這是我的廣告分類模型,我想將數據導出到散列表。

public class AdvertisementCategory { 

private int id; 
private String name, description; 
public List<AdvertisementCategory> advertisementCategories; 

public Map<Object, String> advertisementMap = new HashMap<>(); 

public int getId() { 
    return id; 
} 

public void setId(int id) { 
    this.id = id; 
} 

public String getName() { 
    return name; 
} 

public void setName(String name) { 
    this.name = name; 
} 

public String getDescription() { 
    return description; 
} 

public void setDescription(String description) { 
    this.description = description; 
} 

public AdvertisementCategory(int id, String name, String description) { 
    this.id = id; 
    this.name = name; 
    this.description = description; 
} 

public AdvertisementCategory(String name, String description) { 
    this.name = name; 
    this.description = description; 
} 

public AdvertisementCategory() { 

} 

public AdvertisementCategory(int id, String name) { 
    this.id = id; 
    this.name = name; 
} 

}

回答

2

你以某種方式設法實現對一個不存在的問題相當複雜的解決方案。

使用Swing的MVC原則,您可以直接將AdvertisementCategory添加到列表模型中,並實現ListCellRenderer以從AdvertisementCategory實例中提取顯示值,該實例應顯示在JList本身中。然後在JList上調用getSelectedValue()將爲您提供AdvertisementCategory實例,並且您可以訪問其所有內容。

+0

不,但您可以自己使用Google,並找到大量優秀的教程。 – jarnbjo