Extends AbstractTableModel and populate jTable dynamically

百般思念 提交于 2019-12-25 09:40:13


Basically, I'm working on a Client Server Architecture so Objects can be modified externally by some Clients.

I have a bank :

public class Bank{
    private List<BankingOperation> operationList = new ArrayList<BankingOperation>();

    public void addOperation(BankingOperation op) {

And my Server :

public class ServerBank extends JFrame {
    private Bank bank;
    private JTable table;
    private OperationTableModel model;

    public ServerBank() {
        this.bank = new Bank();
        this.model= new OperationTableModel(this.bank.getOperationList());
        table = new JTable(model);
        getContentPane().add(new JScrollPane(table), BorderLayout.CENTER);

    public static void main (String args[]) throws Exception {

        ServerBank frame=new ServerBank();

    class OperationTableModel extends AbstractTableModel {

    private static final long serialVersionUID = 1L;
    private List<BankingOperation> operationList;
    public String[] colNames = { "Date", "Login", "Customer","Account", "Operation", "Amount", "Final Balance" };
    public Class<?>[] colTypes = { String.class, String.class, String.class, String.class, String.class, Integer.class,
            Integer.class };

    public OperationTableModel(List<BankingOperation> operationList) {
        this.operationList = operationList;

Clients can add an Operation in the Bank operationList by calling addOperation().

The question is: How can the JTable detect that and refresh the display?

Because Clients are not using the TableModel methods for adding Operations. They have no access to this class. On top of that, I don't know if giving the whole operationList of the Bank in the TableModel constructor is a good idea...


By giving the clients access to the internal list used by the bank, you allow them to do things behind the bank of the bank. A bit like if a real bank gave access to its internal database, instead of forcing all the clients to go through the online bank application.

You should give the clients a reference to an interface which allows them to perform their operations. The implementation of this interface would control that every operation they do is allowed, and does everything necessary.

For example, the addOperation() method of the interface implementation would not only add the operation to the list of operations, but also fire a table model event in order for the table to display this added operation.

This could be done directly, if the bank encapsulates the table model, or indirectly, by having the bank fire a custom "operation added" event. The table model would listen to those events, and fire its own table model event in order for the table to be updated.