2

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?

mKorbel
  • 109,525
  • 20
  • 134
  • 319
soupdiver
  • 3,504
  • 9
  • 40
  • 68

4 Answers4

6

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

Puce
  • 37,247
  • 13
  • 80
  • 152
  • but I'm not extending `AbstractTableModel` I'm using the interface – soupdiver Jun 20 '12 at 12:16
  • 1
    follows 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
  • 2
    Most 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
4
  • 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

Community
  • 1
  • 1
mKorbel
  • 109,525
  • 20
  • 134
  • 319
-1

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

lut
  • 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
-1

Try this (insert after setModel(myTableModel); line):

myJTable.createDefaultColumnsFromModel();

In my case it solved the update issue, while: .repaint(), .invalidate(), .fireTableDataChanged() didn't help.

vvinjj
  • 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