For some strange reason, the solution is to use a scroll box that contains a text area. here is the code:
import java.awt.Component;
import java.awt.Font;
import java.awt.FontMetrics;
import javax.swing.BorderFactory;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
import javax.swing.table.TableCellRenderer;
/**
* This class is a JTextArea renderer for JTables. Traditionally, the idea did
* not work because the preferred size for the JTextArea returned at line<p>
* jTable.setRowHeight(row, (int)getPreferredSize().getHeight());<p>
* was the height of the column. Fortunately, for some reason, everything works
* if the renderer extends JScrollPane.
*
*/
public class TextAreaRenderer extends JScrollPane implements TableCellRenderer {
JTextArea jTextArea = new JTextArea();
/**
* Constructor.
*/
public TextAreaRenderer() {
this.jTextArea.setLineWrap(true);
this.jTextArea.setWrapStyleWord(true);
this.jTextArea.setFont(new Font("Dialog", Font.PLAIN, 12));
setBorder(BorderFactory.createEmptyBorder());
setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_NEVER);
getVerticalScrollBar().setFocusable(false);
getHorizontalScrollBar().setFocusable(false);
setViewportView(this.jTextArea);
}
/**
* @see
* javax.swing.table.TableCellRenderer#getTableCellRendererComponent(javax.swing.JTable,
* java.lang.Object, boolean, boolean, int, int)
*/
public Component getTableCellRendererComponent(JTable jTable, Object obj,
boolean isSelected, boolean hasFocus, int row, int column) {
//Get the length of the text.
String displayString = (String)obj;
this.jTextArea.setText(displayString);
FontMetrics fontMetrics = this.jTextArea.getFontMetrics(this.jTextArea.getFont());
int textLength = SwingUtilities.computeStringWidth(fontMetrics, displayString);
//Compute the height.
int width = jTable.getColumnModel().getColumn(column).getWidth();
int numberOfRows = textLength/width;
if (numberOfRows*width < textLength)
numberOfRows++;
this.jTextArea.setRows(numberOfRows);
int rowHeight = (int)getPreferredSize().getHeight();
if (jTable.getRowHeight(row) < rowHeight)
jTable.setRowHeight(row, rowHeight);
return this;
}
}