Getting column names from an AbstractTableModel

dierre picture dierre · Nov 16, 2010 · Viewed 9.1k times · Source

I can't figure out something using the constructor JTable(TableModel dm).

I'm using a LinkedList to manage my data so, to display it, I extended AbstractTableModel:

public class VolumeListTableModel extends AbstractTableModel {

    private static final long serialVersionUID = 1L;
    private LinkedList<Directory> datalist;
    private Object[] columnNames= {"ID", "Directory", "Wildcard"};


    public VolumeListTableModel(){
    }

    public void setDatalist(LinkedList<Directory> temp){
        this.datalist = temp;
    }

    public LinkedList<Directory> getDatalist(){
        return (LinkedList<Directory>) this.datalist.clone();
    }

    public Object[] getColumnNames() {
        return this.columnNames;    
    }

    @Override
    public int getColumnCount() {
        return Directory.numCols;
    }

    @Override
    public int getRowCount() {
        return this.datalist.size();
    }

    @Override
    public Object getValueAt(int row, int col) {

        Directory temp = this.datalist.get(row);

        switch(col){
        case 0:
            return temp.getId();
        case 1:
            return temp.getPath();
        case 2:
            return temp.getWildcard();
        default:
            return null;        
        }
    }

I'm doing something wrong because when I run my GUI I get column names labeled A,*B*,C.

Answer

Codemwnci picture Codemwnci · Nov 16, 2010

There is no method in AbstractTableModel called getColumnNames, so I believe your method is being ignored. The actual method you want to override is the getColumnName method.

Try adding this method to your VolumeListTableModel class

public String getColumnName(int column) {
    return columnNames[column];
}