Reputation: 138
Let's say I have this JTable:
private JScrollPane scrollPane1;
private JTable table;
private DefaultTableModel model;
DefaultTableModel model = new DefaultTableModel();
model.addColumn("Item");
model.addColumn("ID");
model.addColumn("Price");
model.addColumn("Category");
this.scrollPane1 = new JScrollPane();
this.scrollPane1.setBounds(33, 518, 604, 300);
this.contentPane.add(this.scrollPane1);
table = new JTable(model);
this.scrollPane1.setViewportView(table);
I have an Item class, so when I create a new instance of Item, I add the items info to the JTable:
Item item = new Item("Shovel", 1, 123, "Tools");
model.addRow(new Object[]{item.getItem(), item.getID(), item.getPrice(), item.getCategory()});
So far so good. But if I update the Item, for example change the price from 5 to 10, it is not updated in the JTable. So if I for example do:
item.setPrice(10);
It doesnt update in the JTable. I've tried calling model.fireTableDataChanged(); and table.repaint(); but none of them works. It seems like the value in the cell is not associated with the objects value? How would I do this? (First time working with JTables).
Any suggestions? Don't be bothered by the lack of methods etc., I just put this together quickly for this post. EDIT: My Item objects are stored in a HashMap.
Upvotes: 1
Views: 1373
Reputation: 8657
Actually, you are not modifying any cell in the table, the item
object is not associated with your table directly, your making a now values in the table by using the same values from the item
object.
what you has to do is to update the cell itself then by overriding the below method from AbstractTableModel
class:
@Override
public void setValueAt(Object value, int row, int col) { //
Then call
model.fireTableDataChanged();
Upvotes: 1