I have different objects which is used to store the data from DB in an ArrayList<T>
. I got to show records of each in a Table. I use an AbstractTableModel
for first object am working on. The AbstractTableModel
class has an ArrayList<Relation>
and an String[]
of headers.
My question is : How do I create the same AbstractTableModel
that can be used for all objects. I mean if working with Relation, I can have ArrayList<Relation>
, if with Product, can have ArrayList<Product>
..etc. Writing different AbstrastTableModel
for each is not a good idea according to me. The main problem comes with setValueAt
, getValue
, addRow
....
@Override
public void setValueAt(Object value, int row, int col) {
Relation r = data.get(row); // ArrayList<Relation> data
switch (col) {
case 0:
r.setId(value.toString());
break;
case 1: r.setName(value.toString());
break;
case 2: r.setStartBalance((Double)value);
break;
case 3: r.setCurrentBalance((Double)value);
break;
}
}
Any good idea to work on this as a single model that works for all. And can also fire events from here for the table.
I know it is a bit complicated. But the structure is vast and creating new class of AbstractTableModel
and JTable
for each object is also not a good idea.
What do you suggest ?
You can create an abstraction over your multiple data classes such that they expose methods like setValue(int columnNumber, Object Value) and similar getValue() method. Then you can write AbstractTableModel over this new abstraction. Afterwards creating required table model will just require changing the data class in constructor of your model.
For instance you can have an interface:
interface DBRow
{
public void setValue(int columnNumber, Object value);
public Object getValue(int columnNumber);
}
Both Product and Relation classes should implement this and then your model can work on DBRow interface.
You can also consider directly using resultset for populating tables: resultset-to-tablemodel