Search code examples
javaswingjtableabstracttablemodel

Column names don't appear when using AbstractTableModel


Hy. I am trying to build a simple JTable using AbstractTableModel,but the column names don't appear even though I used a JScrollPane.

public class TableModel extends AbstractTableModel{
private String[] columnNames = new String[]{"#","Name","Price","Quantity","Description"};

public TableModel() {
    super();
    System.out.println("constructor");

}

public int getColumnCount() {
    return 0;
}

public int getRowCount() {
    return 0;
}

public Object getValueAt(int rowIndex, int columnIndex) {
    return null;
}

public String getColumnName(int columnIndex) {
    System.out.println("in");
    return columnNames[columnIndex];
}

}

I place the tabel on a JPanel in the following way:

table = new JTable(new TableModel());
add(new JScrollPane(table));

The method getColumnName isn't invoked. Why?


Solution

  • As your column count is zero, there is no need to get column names.

    try

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