0

By default null values are rendered as empty strings in JTable. I'd like to have a default renderer displaying "NULL" when rendering a null value, but only for the String class. The following code works nice for the Object class and also if the renderer is set for specific columns, but fails if set for the String class. Any ideas how to achieve this?

import javax.swing.*;
import javax.swing.table.*;

public class RenderingNull extends JFrame {

  public RenderingNull() {
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setSize(150, 150);
    setLocationRelativeTo(null);

    String headers[] = {"Fruit", "Colour"};
    Object data[][] = {
        {"Tomato", "Red"},
        {"Banana", "Yellow"},
        {"Orange", null},
        {null, "Green"}
      };

    TableModel model = new DefaultTableModel(data, headers);
    JTable table= new JTable(model);
    TableCellRenderer renderer= new NullRenderer();
//    table.setDefaultRenderer(Object.class, renderer);
//    table.getColumn("Fruit").setCellRenderer(renderer);
//    table.getColumn("Colour").setCellRenderer(renderer);
    table.setDefaultRenderer(String.class, renderer);
    JScrollPane scrollPane= new JScrollPane(table);
    add(scrollPane);
    setVisible(true);
  }


  public static void main(String args[]) {
    SwingUtilities.invokeLater(RenderingNull::new);
  }


  class NullRenderer extends DefaultTableCellRenderer {
    @Override
    public void setValue(Object value) {
      setText(value==null ? "NULL" : value.toString());
    }
  }

}
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Jörg
  • 214
  • 1
  • 9

1 Answers1

1

but fails if set for the String class.

By default the getColumnClass(...) method of the JTable and DefaultTableModel returns Object.class.

The table determines the renderer (and editor) based on the value returned from this method.

Therefore by default you can only provide custom rendering at the column level or at the Object.class level (as you have noticed).

If you want special rendering for String.class, then you need to override the getColumnClass(...) method in either of the classes listed above to return String.class.

See: Referencing in a private DefaultTableModel for a simple example.

camickr
  • 321,443
  • 19
  • 166
  • 288