use JList to display TreeMap Objects

1.2k Views Asked by At

I would like to iterate through a TreeMap to add objects to a DefaultListModel and then to a JList. However, only the key values are displayed in the list and not the object. How can I correct this?

see code below:

public class ViewInventoryInterface extends JFrame {
private Inventory theInventory; // reference to back end
private InventoryUPCIterator iter;
private DefaultListModel dlm;
private JList list;
private JScrollPane scroll;

public ViewInventoryInterface(Inventory theInventory) {
    this.theInventory = theInventory;
    iter = theInventory.inventoryUPCIterator(); //returns an iterator for the inventory
    dlm = new DefaultListModel();
    while (iter.hasNext()) {
        dlm.addElement(iter.next());
    }
    list = new JList(dlm);
    scroll = new JScrollPane(list);
    setTitle("Inventory");
    add(scroll);
    setSize(400, 400);
    setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    setLocationRelativeTo(null);
    setVisible(true);

}
}

and this is the class from which the iterator is created

public class InventoryUPCIterator {

private Set<String> keys;
private Iterator<String> iter;

public InventoryUPCIterator(HashMap<String, ItemIndex> inventory) {
    TreeMap<String, ItemIndex> values = new TreeMap<String, ItemIndex>(
            inventory);
    // sorts the index according to the natural ordering of String values
    keys = values.keySet();// returns set of sorted keys
    iter = keys.iterator();
}

public boolean hasNext() {
    return iter.hasNext();
}

public String next() {
    return iter.next();

}

public void reset() {
    iter = keys.iterator();// start again from the beginning
}
}
2

There are 2 best solutions below

0
On BEST ANSWER

You are only adding the key value into the dlm object

while (iter.hasNext()) {
        dlm.addElement(iter.next());
    }

modify the above loop to add the value as well

1
On

Unfortunately you have not showed how do you get the iterator (theInventory.inventoryUPCIterator()). But I believe that you wrote something like map.entries().iterator() that returns iterator of entries (i.e. key-value pairs). Use map.keySet() or key.values() instead or use entry.getKey() when iterating entries.