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:
-
If I am extending a
DefaultTableModelthen 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. -
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.
-
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.
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 ofVector, a supported but obsolescentCollectionthat carries (possibly) needless synchronization overhead.AbstractTableModeloffers much more flexibility in exposing your application’s data model to aJTableview. It should be used in cases for whichDefaultTableModelis unsuitable.Focusing on your question,
JTableimplementsTableModelListener, and it listens to its ownTableModel. An arbitrary number of other views can also listens to the same model;DisplayPanelis an example that listens to anAbstractTableModelnamedCheckModel. YourTableModelshould fire a suitableTableModelEventif it contains the data needed by your view(s) to update themselves. If not, you can define your own event types using the sameEventListenerListmechanism used byJTable, described here, and mentioned here.