Java – cellrenderer and editor reset when new columns are added
I have a table where my columns expand dynamically Initially, I set my table model to 5 columns because the basic information has 5 columns Of the five columns, columns 2 and 3 are buttons (actually they are hyperlinks in the form of buttons), which means that I have set columns 2 and 3 to have my own renderer and editor
table.getColumnModel().getColumn(2).setCellRender(new MyCellRender()); table.getColumnModel().getColumn(2).setCellEditor(new MyCellEditor(table)); //more code for column 3 initializatation
My problem is that sometimes a row may have more than 5 columns, so every time I need to add more columns to the model, I will check it by adding new columns I use
model.addColumn("ColumnName");
Add a new column The problem is that every time I add a row larger than the initial row, my renderer and the editors on columns 2 and 3 are reset / deleted and rendered to default values What do I need to keep columns 2 and 3 BTW columns 2 and 3 are the only columns that always appear as buttons
Solution
To initially create a table, you can use:
JTable table = new JTable(model); table.setAutoCreateColumnsFromModel( false ); table.getColumnModel().getColumn(2).setCellRender(new MyCellRender()); table.getColumnModel().getColumn(2).setCellEditor(new MyCellEditor(table));
Tablecolumnmodel and tablecolumns are automatically created
Now, if you want to add another column, because tablecolumns are not automatically created from the model, you won't lose the custom renderer / editor, but now you need to create tablecolumns manually:
String columnName = "Column X"; model.addColumn( columnName ); // AutoCreate is turned off so create table column here TableColumn column = new TableColumn( table.getColumnCount() ); column.setHeaderValue( columnNamer ); table.addColumn( column );