The first approach that came to my mind is to create a subclass of AbstractTableModel
, and store the data in its private ArrayList<?>
field. In its constructor, query the database with the data you want to show in the table.
If a row is added to the table, an INSERT
statement with the data inserted will be fired to the DB.
If an update to a cell in the table is done, validate if the update is possible. If possible, an UPDATE
will be fired to the DB
If a row is deleted, a DELETE FROM
statement will be fired to the DB.
public class MyTableModel extends AbstractTableModel{
private List<Person> dataSource;
public MyTableModel(){
dataSource = new ArrayList<Person>();
//query the database then add the queried data to the dataSource,
//you should do it in the background, using SwingWorker
//call fireTableRowsInserted with proper arguments
}
@Override
public int getColumnCount() {
return 3;
}
@Override
public int getRowCount() {
return dataSource.size();
}
@Override
public Object getValueAt(int row, int col) {
Object retVal = null;
if(col == 0)dataSource.get(row).getFirstName();
else if(col == 1)dataSource.get(row).getLastName();
else if(col == 2)dataSource.get(row).getOccupation();
return retVal;
}
@Override
public void setValueAt(Object value, int row, int col){
//validate if the update is possible, if yes proceed
//update the value in the DB
//update the value in the arraylist
//call super.setValueAt(value, row, col);
}
public void addRow(Person p){
//validate if the person is insertable, if yes proceed
//INSERT the person to the DB
//add the person to the arraylist
//call fireTableRowsInserted
}
public void deleteRow(int row){
//call fireTableRowsDeleted
}
}