Search code examples
javaswingtablemodelabstracttablemodeldefaulttablemodel

Java - TableModelListeners and DataModelEvents


When should I create my own TableModelListeners and DataModelEvents?

I know the difference and use of a DefaultTableModel, AbstractTableModel and TableModel.

I have seen in many online Java examples where TableModelListeners and DataModelEvents are explicitly created while creating a class (custom model) that extends either the DefaultTableModel and the AbstractTableModel class.

This is my understanding:

  1. If I am extending a DefaultTableModel then this model already knows how to create DataModelEvents and the TableModelListeners (so that I do not have to add them) listening/observing to these events and also knows to notify the TableModelListeners.

  2. If I am extending an AbstractTableModel then this model already knows how to create DataModelEvents and the TableModelListeners (so that I do not have to add them) listening/observing to these events. But I have to explicitly invoke the firetablechanged() or similar methods to notify the TableModelListeners about the event.

  3. If I am implementing a TableModel then this model already knows how to create DataModelEvents but does not have any TableModelListeners (so that I have to add them) listening/observing to these events. And also I have to explicitly invoke the firetablechanged() or similar methods to notify the TableModelListeners about the event.


Solution

  • I defer to @mKorbel on DefaultTableModel, which is well suited to cases that can rely on its straightforward mutators. It is limited by the internal use of Vector, a supported but obsolescent Collection that carries (possibly) needless synchronization overhead.

    AbstractTableModel offers much more flexibility in exposing your application's data model to a JTable view. It should be used in cases for which DefaultTableModel is unsuitable.

    Focusing on your question, JTable implements TableModelListener, and it listens to its own TableModel. An arbitrary number of other views can also listens to the same model; DisplayPanel is an example that listens to an AbstractTableModel named CheckModel. Your TableModel should fire a suitable TableModelEvent if it contains the data needed by your view(s) to update themselves. If not, you can define your own event types using the same EventListenerList mechanism used by JTable, described here, and mentioned here.