Search code examples
javaswingjtableabstracttablemodel

JTable Cell Isn't Updated On Enter Click


I have an app that has a JTable of some data.. So I add the data and it appears well.. But when I try to edit a cell, I can edit it but when I click enter or tab to save the new content it reflects as it was earlier.. I don't know why that happens.. I searched online but with no hope.. :(

Here is the Table Model class :

public class TableModel extends AbstractTableModel {

String[] columnNames = { "Col1", "Col2", "Col3", "Col4", "Col5", "Col6" };

private List<Entry> db;
JTable table;

public TableModel(JTable table) {
    this.table = table;
}

public void addRow(Entry entry) {
    db.add(entry);
    fireTableRowsInserted(db.size() - 1, db.size() - 1);
    table.editCellAt(db.size() -1, 0);
}

@Override
public boolean isCellEditable(int row, int column) {
    return true;
}

public void setData(List<Entry> db) {
    this.db = db;
}

@Override
public String getColumnName(int column) {
    return columnNames[column];
}

@Override
public int getColumnCount() {
    return 6;
}

@Override
public int getRowCount() {
    return db.size();
}

@Override
public Object getValueAt(int row, int col) {
    Entry entry = db.get(row);

    try {
        switch (col) {
        case 0:
            return entry.getItem();
        case 1:
            return entry.getTransPayment();
        case 2:
            return entry.getEquipPayment();
        case 3:
            return entry.getGasPayment();
        case 4:
            return entry.getEquipSparePayment();
        case 5:
            return entry.getTransSparePayment();
        case 6:
            return entry.getTotal();
        }
    } catch (Exception e) {
        fireTableDataChanged();
    }


    return null;
}


}

The question is : Do I need to add any custom methods or code to do what I mentioned ?


Solution

  • but when I click enter or tab to save the new content it reflects as it was earlier..

    Your TableModel doesn't implement the setValueAt(...) method so the data from the editor is never saved.

    @Override
    public void setValueAt(Object value, int row, int column)
    {
        Entry entry = db.get(row);
    
        switch (column)
        {
            case 0: entry.setItem(value); break;
            case 1: entry.setTransPayment(value); break;
            ...
        }
    
        fireTableCellUpdated(row, column);
    }