Search code examples
javaswingjtabletablemodeldefaulttablemodel

Change TableModel structure


so the scenario is that I've got a JTable with a number of JComboBox's as cells. On the selection of an element of a JComboBox, there needs to be a change in the structure of the Table Model. I've also got an 'output table' below which listens to the selection of the JComboBox's and re-validates accordingly, because of this, I need to keep the model of the query table the same so that it can reuse the listener. How can I change the structure of the Table Model?

DefaultTableModel QueryTableModel = new DefaultTableModel(dropDownUserSelection, resultsListHeadings );     
queryTable.setModel(QueryTableModel);

JComboBox box = new JComboBox(boxModel);      
queryTable.getColumnModel().getColumn(i).setCellEditor(new DefaultCellEditor(box));

I apologize if I am asking a question which has already been asked elsewhere, but I've had a poke around and couldn't find what I was looking for.

Thanks


Solution

  • The TableModel has the responsibility for notifying the parent table (or anybody listening) of changes to the model.

    The general events available are data changed, cell updated, row inserted/removed and structure changed.

    The "structure changed" tells the parent table that the structure of the table model (the number of columns and/or column names and/or types has changed) and it should completely update itself.

    There are a number of ways you could achieve this. You could have the existing table model change it self accordingly and fire a "structure changed" event or you could construct a new table model and apply it to the JTable, depending on your needs.