How to use setValueAt, when I change cell in column in JTable

GoldenScrew picture GoldenScrew · Aug 1, 2016 · Viewed 12.3k times · Source

I have JTable with rows and columns, I need when I edited any cell in column with index 4 -> should changes "VALUE" in the same row, but next column with index 5. I have next code, but it doesn't work

table.getModel().addTableModelListener(new TableModelListener() {
        public void tableChanged(TableModelEvent e) {
            if (table.getSelectedRow()>=0) {
                try {
                    if (table.getSelectedColumn()==4){
                            
                        table.setValueAt("VALUE", 0, 0);
                    }
                } catch (ArrayIndexOutOfBoundsException ee){
                     ee.printStackTrace();
                }
            }
         }
    });

It has an error:

at MainFrame$3.tableChanged(MainFrame.java:188) at javax.swing.table.AbstractTableModel.fireTableChanged(Unknown Source) at javax.swing.table.AbstractTableModel.fireTableCellUpdated(Unknown Source) at javax.swing.table.DefaultTableModel.setValueAt(Unknown Source) at javax.swing.JTable.setValueAt(Unknown Source)

Because it has infinite cycle. Help me, please.

My Table

Answer

Catalina Island picture Catalina Island · Aug 1, 2016

It looks like column 5 depends on column 4. You can override setValueAt() and update the next column in each row like this:

@Override
public void setValueAt(Object object, int row, int col) {
    super.setValueAt(object, row, col);
    int releases = ((Integer) object).intValue();
    int tracksToDownload = releases * …;
    if (col == 4) {
        super.setValueAt(tracksToDownload, row, col + 1);
    }
}

I'm not sure how you calculate tracksToDownload, but you can read the value of other columns in the same row using super.getValueAt().