Reputation: 373
I'm using this code for my application: https://stackoverflow.com/a/8187799. I need to display a table with custom titles on the columns AND the rows, hence the JTableRowHeader
.
I understand how to change the rows name with this code, but I can't find where I'm supposed to change the column's name. I'm kinda struggling with this since I'm not really familiar with the concept.
I tried to add this code in the model = new DefaultTableModel()
but it doesn't work, the columns are still labelled as A
, B
, C
, etc.:
@Override
public String getColumnName(int column) {
switch (column) {
case 0: //First column name:
return "Name1";
case 1: //Second column name:
return "Name2";
//case 2: More names ....
default: // other columns that are not defined above
// using default in a switch statement is always the best practice
return "";
}
}
EDIT: My code is the same as the one that I linked, except that I added the method getColumnName(int index)
here, but it doesn't work:
model = new DefaultTableModel() {
private static final long serialVersionUID = 1L;
@Override
public int getColumnCount() {
return 1;
}
@Override
public boolean isCellEditable(int row, int col) {
return false;
}
@Override
public int getRowCount() {
return JTableRow.this.getRowCount();
}
@Override
public Class<?> getColumnClass(int colNum) {
switch (colNum) {
case 0:
return String.class;
default:
return super.getColumnClass(colNum);
}
}
@Override
public String getColumnName(int column) {
return "test";
}
};
Upvotes: 0
Views: 1432
Reputation: 88757
If you have a look at the code you seem to have copied you'll notice that there are 2 tables being used: table
for the actual data and headerTable
for the row headers. The model you've been changing is used for headerTable
only so it won't affect the columns you see since those are provided by table
.
I won't/can't comment on why 2 tables are used (it still seems odd) so I'll just focus on the column names: set them on table
.
One way would be to provide your own table model, another might be to readjust them afterwards:
for( int i = 0; i < table.getColumnCount(); i++ ) {
table.getColumnModel().getColumn( i ).setHeaderValue( "Column " + i );
}
Upvotes: 2