javaswingjtableabstracttablemodel

Initialize column names in AbstractTableModel


I want to initialize my model. Here is an extract of my main class where I create my GUI items:

public class IceIHM extends JFrame{

List<String> listInit = new ArrayList<String>() { 
{ add("None"); add("None"); add("None"); add("None"); add("None");add("None"); add("None"); }};

String[] tableauObjectTitle = {"Name (OBJECT)","Extended Name","Reference", "Entity Type","Relation", "Extended Relation","PMID"};
String[] tableauSubjectTitle = {"Name (SUBJECT)","Extended Name","Reference", "Entity Type","Relation", "Extended Relation","PMID"};

List<List<String>> dataObject = new ArrayList<List<String>>(){ 
{ add(listInit); add(listInit);}};

List<List<String>> dataSubject = new ArrayList<List<String>>(){ 
{ add(listInit); add(listInit);}};

ModelTableau modelObject = new ModelTableau(dataObject,tableauObjectTitle);
ModelTableau modelSubject = new ModelTableau(dataSubject, tableauSubjectTitle);

JTable tableauObject = new JTable(modelObject);
JTable tableauSubject = new JTable(modelSubject);

Here is my class ModelTableau:

public class ModelTableau extends AbstractTableModel{

private List<List<String>> data = new ArrayList<List<String>>();

private String[] headers;;

public ModelTableau(List<List<String>> data, String[] headers){
    super();
    this.data=data;
    this.headers=headers;
}

public int getRowCount() {
    return data.size();
}

public int getColumnCount() {
    return headers.length;
}

public Object getValueAt(int rowIndex, int columnIndex) {
    return data.get(rowIndex).get(columnIndex);
}

public void removeRow(int row) {
    data.remove(row);
    fireTableRowsDeleted(row, row);
}

public void addRow(List<String> listData) {
    data.add(listData);
    fireTableRowsInserted(data.size()-1, data.size()-1);

}

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

}

Data are well initialized, but not my headers. Can anyone help me to find my mistake?


Solution

  • Override getColumnName(), as shown here, and return headers[col].

    @Override
    public String getColumnName(int col) {
        return headers[col];
    }