javaswingjtabledefaulttablemodel

DefaultTableModel, add row, dynamic number of columns


As above, I don't know how many columns will be in a row, so obviously I'm running into issues with the String[] array. There will be at least 2 columns - that's a given.

How do I work around this limitation?

DefaultTableModel tableModel = new DefaultTableModel(0,1+queryResult.size());



Object[] row = {t.getDate(),'some data'};

tableModel.addRow(row);

view.getPriceHistoryTable().setModel(tableModel);

but if queryResult.size() is bigger than 1 then instead I want to do:

Object[] row = {t.getDate(),'some data','more data'};

tableModel.addRow(row);

view.getPriceHistoryTable().setModel(tableModel);

and so on...


Solution

  • The size of an array doesn't have to be a compile time constant:

    int colCount = 1 + queryResult.size();
    
    String[] row = new String[colCount];
    row[0] = t.getDate();
    
    for(int i = 1; i < row.length; i++) {
        row[i] = "some data"; // or get data from somewhere else
    }
    
    tableModel.addRow(row);