How can I have multi-line text in a JTable cell?

Sandip Chitale

If you are using the DefaultCellRenderer simply split up the lines using a syntax like this -

"<html><body>Line One<br>Line two<br>Line Three</body></html>"

This works because the DefaultCellRenderer is a subclass of JLabel which supports simple HTML rendering.

You may return the value like this from tableModel.getvalueAt(row, col) in the first place. However the same (HTMLized) text will be shown in the CellEditor also. Therefore a better way is to convert the lines into the HTML syntax in the custom DefaultCellRenderer subclass's

public Component getTableCellRendererComponent(JTable table,
  Object value,
  boolean isSelected,
  boolean hasFocus,
  int row,
  int column);
overridden method.

You will have to deal with the table's row height also.

0 Comments  (click to add your comment)
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.