Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: Java
Expertise: Advanced
May 29, 2003



Building the Right Environment to Support AI, Machine Learning and Deep Learning

Extend Swing's JTable to Support Rendering of Different Cell Types in a Column

The basic JTable rendering mechanism supports a single renderer for all cells in a column. The Column Renderer may be set in the TableColumn class. If the TableColumn Renderer is null, the JTable looks up the Renderer based on the Column Class. The Column Class is then determined by the TableModel getColumnClass() method.

Both these approaches assume all values in a column are of the same type, prohibiting the rendering of cell values of different types in a column

To extend the JTable to support the display of cells of different types in one column, sublass JTable. Then, override the getCellRenderer() method to look up the appropriate renderer at run-time, based on the type of the value in the cell.

public class JMyTable  extends JTable{

 public TableCellRenderer getCellRenderer(int row, int column) {
  Object value = getValueAt(row,column);
  if (value !=null) {
    return getDefaultRenderer(value.getClass());
  return super.getCellRenderer(row,column);
Lara D'Abreo
Thanks for your registration, follow us on our social networks to keep up-to-date