0

Is it possible to change AbstractTableModel column names dynamically?

I am trying to implement setColumnName(0, "Speed rpm") method.

public class MyModel extends AbstractTableModel {

private String[] columnNames = {"Speed", "Pressure",
    "Force"};
public ArrayList<Values> list;

public MyModel() {

    list = new ArrayList<Values>();
}

public void setColumnName(int i, String name) {
    columnNames[i,name];
}
@Override
public int getRowCount() {
    return list.size();
}

@Override
public int getColumnCount() {
    return columnNames.length;
}

@Override
public Object getValueAt(int rowIndex, int columnIndex) {
    throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}

}

Trevor
  • 7,777
  • 6
  • 31
  • 50
Vijay Vennapusa
  • 169
  • 3
  • 15

2 Answers2

3

Change

public void setColumnName(int i, String name) {
    columnNames[i,name];
}

to

public void setColumnName(int i, String name) {
    columnNames[i] = name;
    fireTableStructureChanged();
}

Following (always)good advices from @camickr

Invoking the fireTableStructureChanged() method will cause all custom renderers/editors to be lost. You can use the table.setAutoCreateColumnsFromModel(..) method when you create the table to prevent this from happening

nachokk
  • 14,363
  • 4
  • 24
  • 53
  • AFAIK, a TableModelEvent will also have to be fired to notify the view that the header row has been changed. – JB Nizet Feb 21 '14 at 15:06
  • invoking the fireTableStructureChanged() method will cause all custom renderers/editors to be lost. – camickr Feb 21 '14 at 15:39
  • @camickr i see then `AbstractTableModel` doesn't provide any method to notfiy that only a column name change – nachokk Feb 21 '14 at 15:42
  • 1
    Yes, I was just providing a warning to the OP that by using that method the table is recreated which means the renderer/editors are lost and the table columns are reordered back to their original state and any sorting of the data in the table is lost. You can use the `table.setAutoCreateColumnsFromModel(..)` method when you create the table to prevent this from happening. – camickr Feb 21 '14 at 15:57
  • @camickr I didn't know that, thanks camickr i added to the answer! – nachokk Feb 21 '14 at 16:14
2

Change the TableColumn:

tableColumn.setHeaderValue(...);
table.getTableHeader().repaint();

You can get the TableColumn by using:

table.getColumn(...); // or
table.getColumnModel().getColumn(...);
camickr
  • 321,443
  • 19
  • 166
  • 288