![]() |
|
[Java] Updating data in JTable when object changes. - Printable Version +- Hack Forums (https://hackforums.net) +-- Forum: Tech (https://hackforums.net/forumdisplay.php?fid=444) +--- Forum: Coding (https://hackforums.net/forumdisplay.php?fid=151) +---- Forum: Software Development (https://hackforums.net/forumdisplay.php?fid=118) +---- Thread: [Java] Updating data in JTable when object changes. (/showthread.php?tid=4654040) |
Updating data in JTable when object changes. - I Freeze - Jan 25, 2015 Hey. Let's say I have this JTable: Code private JScrollPane scrollPane1;I have an Item class, so when I create a new instance of Item, I add the items info to the JTable: Code Item item = new Item("Shovel", 1, 123, "Tools");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: Code item.setPrice(10);Any suggestions? Don't be bothered by the lack of methods etc., I just put this together quickly for this post. * - ☕⚛Austin⚛☕ - Jan 25, 2015 This is a Stack Overflow answer: If you want to notify your JTable about changes of your data, use tableModel.fireTableDataChanged() From the documentation: Notifies all listeners that all cell values in the table's rows may have changed. The number of rows may also have changed and the JTable should redraw the table from scratch. The structure of the table (as in the order of the columns) is assumed to be the same. * - I Freeze - Jan 25, 2015 (Jan 25, 2015 09:58 AM)๖ۣۜ---Abyte ---๖ۣۜ Wrote: This is a Stack Overflow answer: Yeah, I already tried that. The problem is the cell is not associated with the objects variable. It's simply copied. So when I update the object, it's not updated in the cell. I think I have to use an AbstractTableModel, but I'm still trying to figure it out.. * - Dialog - Jan 25, 2015 I haven't worked with JTables a lot, but you could implement the observer design pattern to be notified when your data is changed. Here's a brief example: http://pastebin.com/uqdmyjv0 Instantiating caller will print Code The item has been changed! |