JTable Display Long Text With Linebreak & Word Wrap
Today I searched how to properly display a user note with line break and word wrap in a JTable. By default the table was truncating the note display and ignoring the line breaks in the text. After scouring the internet, I found out it is possible to inject a JTextArea into a table cell by implementing TableCellRenderer. It is also possible to control the height and width of the column from inside the renderer. Below is a class that can be used in the JTable to achieve this functionality:
package com.mr.gui;
import java.awt.Component;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.table.TableCellRenderer;
/**
* Setups the table to properly wrap and display notes in the table
*
*
* @author Paul Zepernick
*/
public class TableCellLongTextRenderer 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);
//set the JTextArea to the width of the table column
setSize(table.getColumnModel().getColumn(column).getWidth(),getPreferredSize().height);
if (table.getRowHeight(row) != getPreferredSize().height) {
//set the height of the table row to the calculated height of the JTextArea
table.setRowHeight(row, getPreferredSize().height);
}
return this;
}
}
It is applied to the table by doing the following:
//needs to be set on the appropriate column indicy myJTable.getColumnModel().getColumn(0).setCellRenderer(new TableCellLongTextRenderer ());
I found out that by using the TableCellRenderer you an actually inject any Swing component into the table. Cool stuff… I was able to use this to inject a panel with a checkbox and a button. More to come on that later…