Question

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 ?

Was it helpful?

Solution

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

OTHER TIPS

In my opinion one AbstractTableModel should only be used for one object type. Maybe you should rethink your data model.

Anyway, the dirty way of solving this could be to use an ArrayList<Object> in your AbstractTableModel and check in your getValue()-method the type with instanceof. Then you can decide per object type which parameter you return of that particular object.

Example:

@Override
public void setValueAt(Object value, int row, int col) {
    Object r = data.get(row);     // ArrayList<Object> data
    switch (col) {
        case 0:
            if (r instanceof Relation) {
               ((Relation)r).setId(value.toString());
            } else {
               // do something with Product
            }
            break;
    }
}

Could that work for you?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top