title: How to wrap lines in a jtable cell?
body: <p>I'm trying to implement a custom TableRenderer as described in <a href="http://java.sun.com/docs/books/tutorial/uiswing/components/table.html#renderer" rel="noreferrer">this tutorial</a>. 
  I'd like to have the renderer line-wrap each text that is to long for the given cell. 
  The idea is, to use a TextArea as renderer, as it supports line wrapping. However, the following code does not behave as expected:</p>
  
  <pre><code>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);         
          return this;
      }
  
  }
  </code></pre>
  
  <p>I set this renderer with </p>
  
  <pre><code>table.setDefaultRenderer(String.class, new LineWrapCellRenderer());
  </code></pre>
  
  <p>But the cell entries stay unwrapped.
  If I add <code>this.setBackground(Color.YELLOW)</code> to the <code>getTableCellRendererComponent()</code> method, 
  all cells are yellow as expected, but not wrapped.</p>
  
  <p>Any ideas? </p>
  
  <p><strong>UPDATE:</strong> As Michael Borgwardt stated in the comments, the problem is not the line wrap, but the row height: JTables rows are fixed size, so if a cell is getting higher (cause the text is now multi-lined), we have to increase the row height.
  But how much? I will check if this is worth another SO-question. If not, I will add this solution here.</p>
  
  <p><strong>Update2:</strong> The following code will determine the row height (if placed in <code>getTableCellRendererComponent()</code>): </p>
  
  <pre><code>int fontHeight = this.getFontMetrics(this.getFont()).getHeight();
  int textLength = this.getText().length();
  int lines = textLength / this.getColumns() +1;//+1, cause we need at least 1 row.           
  int height = fontHeight * lines;            
  table.setRowHeight(row, height);
  </code></pre>