I've got a class which implements the TableModel Interface.
When I call setModel on my jTable and set my class as the model and then call jTable.updateUI();
everything is fine.
But in some circumstances I want to change the model with a different structure. Displaying the data still works fine but my columns are not updated. Is there a way of forcing my table to also refresh the columns from new model?
-
3Your model implementation is incorrect. Application code _never_ calls updateUI. – kleopatra Jun 20 '12 at 12:16
4 Answers
The model needs to fire the according event, e.g.: fireTableStructureChanged, if both the data and the structure changed.
http://docs.oracle.com/javase/tutorial/uiswing/components/table.html#fire

- 37,247
- 13
- 80
- 152
-
-
1follows link (added +1) this answer is correct to your too wide question, for better help sooner post an [SSCCE](http://sscce.org/) – mKorbel Jun 20 '12 at 12:19
-
2Most likely, you really should. DefaultTableModel is a very data centric approach rather than an Object Oriented approach, which leads to many design issues. A custom model (usually based on AbstractTableModel) on the other hand can wrap around a list of objects. – Puce Jun 20 '12 at 12:20
-
You write you have a class which implements TableModel. Then you have to make sure to notify the listeners if there were some changes. AbstractTableModel provides some helper methods. – Puce Jun 20 '12 at 12:24
jTable.updateUI();
is Look and Feel relevant method, don't use that
I've got a class which implements the TableModel Interface.
you have to override right notifiers for methods from
TableModel
use
DefaultTableModel
, there are all notifiers implemented in the API,all updates must be done on
EventDispatchThread
-
But my model also extends from `Observer` so I cannot simply change to also extending `DefaultTableModel` – soupdiver Jun 20 '12 at 12:26
-
1java.util.Observer is an interface or what Observer are you talking about? – Puce Jun 20 '12 at 12:32
-
If like me you are just writing a small hack, you may consider using the .repaint() method, instead of the .updateUI() method.
I used this because I don't use a TableModel, but I just have data in a Object[][], just like in the first example of the sun (well oracle) tutorial

- 1
-
no, repaint isn't needed with a well-behaved model (and note: there's _always_ a model driving the JTable - it might be an immutable implementation, though) – kleopatra Jan 23 '13 at 10:47
Try this (insert after setModel(myTableModel); line):
myJTable.createDefaultColumnsFromModel();
In my case it solved the update issue, while: .repaint(), .invalidate(), .fireTableDataChanged() didn't help.

- 83
- 2
- 9
-
no, that's not a method to call by application code: happens automatically on setModel (provided you did't change the default true value of autoCreateColumns). If it appears to help in your context, something is wrong elsewhere – kleopatra Jan 23 '14 at 00:18