I want to put a String in a JTable that is longer than the given cell-width.
How can I set the rowHeight dynamically so that I can read the whole S
I find it simplest to adjust the row height from inside the component renderer, like this:
public class RowHeightCellRenderer extends JTextArea implements TableCellRenderer
{
public Component getTableCellRendererComponent(JTable table, Object
value, boolean isSelected, boolean hasFocus,
int row, int column) {
setText(value.toString());
// Set the component width to match the width of its table cell
// and make the height arbitrarily large to accomodate all the contents
setSize(table.getColumnModel().getColumn(column).getWidth(), Short.MAX_VALUE);
// Now get the fitted height for the given width
int rowHeight = this.getPreferredSize().height;
// Get the current table row height
int actualRowHeight = table.getRowHeight(row);
// Set table row height to fitted height.
// Important to check if this has been done already
// to prevent a never-ending loop.
if (rowHeight != actualRowHeight) {
table.setRowHeight(row, rowHeight);
}
return this;
}
}
This will also work for a renderer which returns a JTextPane.