What could I add to this code to allow the cell height to dynamically change as I edit the JTextArea
- by Dr. Plaguey
The derived classes I am using
public class TextAreaRenderer extends JTextArea
implements TableCellRenderer {
public TextAreaRenderer() {
setLineWrap(true);
setWrapStyleWord(true);
}
public Component getTableCellRendererComponent(JTable jTable,
Object obj, boolean isSelected, boolean hasFocus, int row,
int column) {
setText((String)obj);
int height_wanted = (int)getPreferredSize().getHeight() + 10;
if (height_wanted != rootJTable.getRowHeight(row))
rootJTable.setRowHeight(row, height_wanted);
return this;
}
}
class TextEditor extends AbstractCellEditor implements TableCellEditor
{
protected JTextArea ta;
String txt;
public TextEditor()
{
ta = new JTextArea();
}
//Implement the one CellEditor method that AbstractCellEditor doesn't.
public Object getCellEditorValue()
{
return ta.getText();
}
// Implement the one method defined by TableCellEditor.
public Component getTableCellEditorComponent(javax.swing.JTable table, Object value,boolean isSelected, int row, int column)
{
txt = value.toString();
ta.setText(txt);
ta.setLineWrap(true);
return new JScrollPane(ta);
}
public boolean isCellEditable(EventObject anEvent)
{
return true;
}
}
Set column renderer and editor
rootJTable.getColumnModel().getColumn(1).setCellRenderer(new TextAreaRenderer());
rootJTable.getColumnModel().getColumn(1).setCellEditor(new TextEditor());