-1

I want to create a swing table with cell's line wrapping, so I have created the following renderer that makes use of a textarea. The problem is that it creates an infinite loop if I set the row height using the setRowHeight method inside the renderer. I would like to know if there is a way of achieving this (cell line wrap without infinite loop).

final class RenderTextAreaMessage extends DefaultTableCellRenderer {

    JTextArea textareaMessage;

      @Override 
      public Component getTableCellRendererComponent(JTable aTable, Object aNumberValue, boolean aIsSelected, 
        boolean aHasFocus, int aRow, int aColumn ) {  
         System.out.println("aa");
         String value = (String)aNumberValue;

         textareaMessage = new JTextArea();

         textareaMessage.setLineWrap(true);
         textareaMessage.setWrapStyleWord(true);
         textareaMessage.setText(value);
         textareaMessage.setBorder(null);
         textareaMessage.setMargin(null);

        Component renderer = super.getTableCellRendererComponent(
                aTable, aNumberValue, aIsSelected, aHasFocus, aRow, aColumn
        );

          Font fontType = textareaMessage.getFont();
          FontMetrics fontMet = textareaMessage.getFontMetrics(fontType);
          int fheight = fontMet.getHeight();

          int lineCount = textareaMessage.getLineCount();
          int rowHeight = lineCount * fheight;

        aTable.setRowHeight(aRow,rowHeight+6);      

        return textareaMessage;
      }
}
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
v8rs
  • 197
  • 4
  • 17
  • You apparently did not notice the message in upper case on the [tag:table] tag which states *"DO NOT USE THIS TAG;"*. Please **read** the tags before slapping them on a post in future. – Andrew Thompson Jun 08 '16 at 14:04

1 Answers1

2

I've created a method to update the row height depended on the current row height of renderers. But to use it you need to set the correct height (probably using the method setPreferredSize()) for your renderer. Simply call this method when your table content is up-to-date.

public static void updateRowHeight(JTable table) {
    final int rowCount = table.getRowCount();
    final int colCount = table.getColumnCount();
    for (int i = 0; i < rowCount; i++) {
        int maxHeight = 0;
        for (int j = 0; j < colCount; j++) {
            final TableCellRenderer renderer = table.getCellRenderer(i, j);
            maxHeight = Math.max(maxHeight, table.prepareRenderer(renderer, i, j).getPreferredSize().height);
        }
        table.setRowHeight(i, maxHeight);
    }
}
Sergiy Medvynskyy
  • 11,160
  • 1
  • 32
  • 48