I\'m trying to implement a custom TableRenderer as described in this tutorial. I\'d like to have the renderer line-wrap each text that is to long for the given cell. The i
I stumbled in this same problem, and I needed to modify a little the code that it was written here, so I attach my own version:
import java.awt.Component;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.table.TableCellRenderer;
public class LineWrapCellRenderer extends JTextArea implements TableCellRenderer {
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus,
int row, int column) {
this.setText((String) value);
this.setWrapStyleWord(true);
this.setLineWrap(true);
int fontHeight = this.getFontMetrics(this.getFont()).getHeight();
int textLength = this.getText().length();
int lines = textLength / this.getColumnWidth();
if (lines == 0) {
lines = 1;
}
int height = fontHeight * lines;
table.setRowHeight(row, height);
return this;
}
}