我想迭代一个TreeMap,将对象添加到DefaultListModel,然后再添加到JList。但是,只有键值显示在列表中而不是对象中。我怎么能纠正这个?
请参阅以下代码:
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);
}
}
这是创建迭代器的类
公共类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
}
}
答案 0 :(得分:0)
您只是将键值添加到dlm对象
中while (iter.hasNext()) {
dlm.addElement(iter.next());
}
修改上面的循环以添加值
答案 1 :(得分:0)
不幸的是,您还没有展示如何获得迭代器(theInventory.inventoryUPCIterator()
)。但我相信你写了类似map.entries()。iterator()的东西,它返回条目的迭代器(即键值对)。使用map.keySet()或key.values()代替或在迭代条目时使用entry.getKey()
。