Search code examples
javaswingjtableheader

Change column header in JTable if i know column position


Can I change column header in Jtable tab from "Name" to "Surname" if I know column position? I want to change column name in second or first tab, not last one.

With this code I can change only column header in last tab. I have 4 tabs.

JTableHeader th = table.getTableHeader();
TableColumnModel tcm = th.getColumnModel();
TableColumn tc = tcm.getColumn(0);
tc.setHeaderValue( "???" );
th.repaint();

Solution

  • You only have to replace your column index by the use of column identifier :

    JTableHeader th = table.getTableHeader();
    TableColumnModel tcm = th.getColumnModel();
    TableColumn tc = tcm.getColumn(tcm.getColumnIndex("Name")); // may not work, see note below
    tc.setHeaderValue( "???" );
    th.repaint();
    

    The TableColumnModel#getColumnIndex(Object) works with a column identifier. Most of the time, column identifier and column header value are identical. However, in some cases, they can differ (typically when using i18n for column header). But in this case, i guess you have identified your column with a constant id.