簡體   English   中英

從Hashmap填充JList並重新獲取密鑰

[英]Populating JList from Hashmap and retriving key

如何從HashMap填充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);
    }
}

這是My AdvertisementCategory模型,我想將數據導出到hashmap。

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

}

您正試圖為不存在的問題實施一個相當復雜的解決方案。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM