Question

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.
}

}

Was it helpful?

Solution

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

OTHER TIPS

Change the TableColumn:

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

You can get the TableColumn by using:

table.getColumn(...); // or
table.getColumnModel().getColumn(...);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top