1

I've spent quite a while trying to figure out a way of adding a new row to a JTable, initially by looking for methods on the following model:

TableModel model = new DefaultTableModel(data, tabs);

However, some quick searching lead me to find that the method addRow was within the DefaultTableModel class instead. So changing it to the following was successful:

DefaultTableModel model = new DefaultTableModel(data, tabs);

However, I've created many successful programs where I have had a pre-built array using TabelModel, so I'm a bit confused as to why I needed to switch to DefaultTableModel to achieve this solution and if there is a reason and a purpose for each? E.g.: Is it okay to simple use a TabelModel with a pre-built array and why does my above implementation of TableModel not come with the methods to add new data?

Thanks!

kleopatra
  • 51,061
  • 28
  • 99
  • 211
mark
  • 2,841
  • 4
  • 25
  • 23
  • 1
    TableModel is an interface, DefaultTableModel is a concrete implementation, that among other things provides a convenient way to add rows. – tenorsax Mar 18 '12 at 19:54
  • @Niles, the reason why `model` does not come with the methods begins in the line: `TableModel model = new DefaultTableModel(data, tabs);` . `model` should be casted to `DefaultTableModel` in order to have the methods implemented in the casted class. In any instantiation of that type you will need to cast your object if you add methods that are not in the implemented class. – Sebastian Mar 18 '12 at 20:18

1 Answers1

4

If you must use your own collection as a nucleus for your table model, then so be it, but then you'll want to extend AbstractTableModel and create your own addRow method that adds the data to the model, and (here's the critical part) that fires the appropriate data change notification method of AbstractTableModel.

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
  • 3
    [`DefaultTableModel`](http://developer.classpath.org/doc/javax/swing/table/DefaultTableModel-source.html) is a handy guide to _appropriate_. – trashgod Mar 19 '12 at 04:00
  • 2
    `AbstractTableModel` provides a lot of stuff that every `TableModel` must have, but the code itself is not very interesting (like listener management). It is a handy class to base a `JTable` on your own data. Use it. – Jakub Zaverka Mar 19 '12 at 11:28