I am trying to get the header on a table to have word wrap. I have managed to do this but the first data row is expanding. The code for the table is:
public class GenerateTable extends JTable {
private JCheckBox boxSelect = new JCheckBox();
private JTableHeader hdGen;
public class LineWrapCellRenderer extends JTextArea implements TableCellRenderer {
private static final long serialVersionUID = 1L;
int rowHeight = 0; // current max row height for this scan
@Override
public Component getTableCellRendererComponent(
JTable table,
Object value,
boolean isSelected,
boolean hasFocus,
int row,
int column)
{
/*
* row < 0 means header
*/
if(row >= 0) {
setWrapStyleWord(false);
return this;
}
setText((String) value);
setWrapStyleWord(true);
setLineWrap(true);
// current table column width in pixels
int colWidth = table.getColumnModel().getColumn(column).getWidth();
// set the text area width (height doesn't matter here)
setSize(new Dimension(colWidth, 1));
// get the text area preferred height and add the row margin
int height = getPreferredSize().height + table.getRowMargin();
// ensure the row height fits the cell with most lines, row = -1 for header
if (column == 2 || height > rowHeight) {
table.setRowHeight(row, height);
rowHeight = height;
}
return this;
}
}
LineWrapCellRenderer lwHeader = new LineWrapCellRenderer();
public GenerateTable(GenerateTableModel model) {
super(model);
this.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
/*
* Select
*/
TableColumn colSelect = this.getColumnModel().getColumn(0);
colSelect.setCellEditor(new DefaultCellEditor(boxSelect));
colSelect.setPreferredWidth(60);
/*
* category
*/
this.getColumnModel().getColumn(1).setResizable(false);
this.getColumnModel().getColumn(1).setPreferredWidth(200);
/*
* Amount values
*/
for (int i=2;i<model.getColumnCount();i++) {
colSelect = this.getColumnModel().getColumn(i);
colSelect.setPreferredWidth(100);
colSelect.setResizable(false);
colSelect.setHeaderRenderer(lwHeader);
}
}
}
The output is:
I have followed the code through in debug and LineWrapCellRenderer is not being called for the data lines. If I take the code out I get a normal table but no wrap on the header. Is this a recognised problem or am I missing something?
Any help appreciated