1 year ago
#321151
PrOF
Displaying a LinkedHashMap in a JTable
I have an Order object which among other things stores a LinkedHashList (Product : amount). I use a LinkedHashList because I specifically want to keep the insertion order.
public class Order {
private Map<Product, Integer> productMap;
public Order() {
this.productMap = new LinkedHashMap<>();
}
public Map<Product, Integer> getMap() {
return this.productMap;
}
}
In my GUI i've created a JTable with an OrderTableModel like so:
private Class<?>[] columnClasses = { String.class, Double.class, Integer.class };
private String[] columnNames = { "Name", "Price", "Amount" };
private Order currentOrder;
public OrderTableModel(Order order) {
this.currentOrder = order;
}
// [...]
@Override
public Object getValueAt(int rowindex, int columnIndex) {
Product selectedProduct = (Product) this.currentOrder.getMap().keySet().toArray()[rowIndex];
switch (columnIndex) {
case 0:
return selectedProduct.getName():
case 1:
return selectedProduct.getPrice();
case 2:
return this.currentOrder.get(selectedProduct);
}
However I understand that Map
s weren't made to be accessed by index and that (Product) this.currentOrder.getMap().keySet().toArray()[rowIndex]
is a hack.
This also has the disadvantage of making it quite slow getting a Product object from a row selection in the JTable (get the selected row, iterate again).
I've thought about using two ArrayLists linked by index but that also looks like a hack to me.
So is there a decent way to display a Map in a JTable without going though all these hoops?
java
swing
jtable
tablemodel
0 Answers
Your Answer