What could I add to this code to allow the cell height to dynamically change as I edit the JTextArea

Posted by Dr. Plaguey on Stack Overflow See other posts from Stack Overflow or by Dr. Plaguey
Published on 2010-04-09T03:19:34Z Indexed on 2010/04/09 3:23 UTC
Read the original article Hit count: 424

Filed under:
|
|
|

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());

© Stack Overflow or respective owner

Related posts about java

Related posts about jtable